如何一次grep两种模式 [英] How to grep two patterns at once
问题描述
通常,我必须在命令行中执行此操作,在此我将管道输送到grep并希望匹配两个不同的表达式. (一个OR匹配A OR B.)
例如,我想grep foo [0-9] +或bar [0-9] +的generate_out输出.我当然可以执行两次:
generate_out| grep "foo[0-9]+"
generate_out| grep "bar[0-9]+"
,但是generate_out通常很昂贵,我不想运行两次(或存储它的输出).相反,我只想使用一个表达式:
generate_out| grep "foo[0-9]+ OR bar[0-9]+"
这当然是行不通的,但是我想要一个等效的表达式.
在正则表达式中使用替代项:
generate_out | grep -E '(foo|bar)[0-9]+'
使用-E
启用ERE功能,这是其中之一. (默认情况下,grep仅支持BRE;某些BRE实现(例如GNU的实现)可能具有启用ERE功能的特殊语法;在GNU情况下,BRE中的\|
等效于ERE中的|
;但是,依靠这样的扩展而不是仅仅正确地开启ERE并不是可移植的.
egrep
是grep -E
的向后兼容同义词;但是, POSIX仅将后者指定为要求.>
Often times I have to do so commandline thing where I pipe to grep and want matches for two different expressions. ( An OR match A OR B. )
For example I want to grep the output of generate_out for either foo[0-9]+ or bar[0-9]+. I of course could just execute twice:
generate_out| grep "foo[0-9]+"
generate_out| grep "bar[0-9]+"
but often generate_out is expensive and I would rather not want to run it twice ( or store it's output ). Rather I would like to just use one expression:
generate_out| grep "foo[0-9]+ OR bar[0-9]+"
of course this will not work but I would like the equivalent expression which will.
Use an alternation in your regex:
generate_out | grep -E '(foo|bar)[0-9]+'
The use of -E
enables ERE features, of this which is one. (By default, grep only supports BRE; some implementations of BRE -- such as GNU's -- may have special syntax for enabling ERE features; in the GNU case, \|
in BRE is equivalent to |
in ERE; however, it's not portable to rely on such extensions instead of just turning on ERE properly).
egrep
is a backwards-compatibility synonym for grep -E
; however, only the latter is specified as a requirement by POSIX.
这篇关于如何一次grep两种模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!