使用带有正则表达式的grep来过滤匹配

Hor*_*ude 41 grep

我正在尝试使用grep和-v进行反向匹配,并使用-e进行正则表达式.我无法正确使用语法.

我正在尝试类似的东西

tail -f logFile | grep -ve "string one|string two"
Run Code Online (Sandbox Code Playgroud)

如果我这样做它不会过滤如果我将其更改为

tail -f logFile | grep -ev "string one|string two"
Run Code Online (Sandbox Code Playgroud)

我明白了

grep: string one|string two: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我尝试使用()或引号,但一直无法找到有效的东西.

我怎样才能做到这一点?

Ada*_*eld 64

问题是,默认情况下,你需要转义你的|以获得适当的交替.也就是说,grep将"foo | bar"解释为仅匹配文字字符串"foo | bar",而模式"foo\| bar"(带有转义的|)匹配"foo"或"bar".

要更改此行为,请使用-E标志:

tail -f logFile | grep -vE 'string one|string two'
Run Code Online (Sandbox Code Playgroud)

或者,使用egrep,相当于grep -E:

tail -f logFile | egrep -v 'string one|string two'
Run Code Online (Sandbox Code Playgroud)

此外,-e是可选的,除非您的模式以文字连字符开头.grep自动将第一个非选项参数作为模式.


Jay*_*Jay 5

使用-e时需要转义管道符号:

tail -f logFile | grep -ve "string one\|string two"
Run Code Online (Sandbox Code Playgroud)

编辑:或者,正如@Adam指出的那样,你可以使用-E标志:

tail -f logFile | grep -vE "string one|string two"
Run Code Online (Sandbox Code Playgroud)