使用正则表达式的grep过滤掉匹配 [英] Using grep with regular expression to filter out matches

查看:192
本文介绍了使用正则表达式的grep过滤掉匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用grep和-v来进行反转匹配,而-e用于正则表达式。我无法正确地获得语法。



我正在尝试类似于

  tail -f logFile | grep -vestring one | string two

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

  tail -f logFile | grep -evstring one | string two

我得到

  grep:string one | string two:没有这样的文件或目录

我试过使用()或引号,但一直未能找到任何可行的方法。



我该怎么做? / p>

解决方案

问题在于,默认情况下,您需要跳过|以获得适当的替代方案。也就是说,grep只将foo | bar解释为与文本字符串foo | bar匹配,而模式foo \ | bar(带有escape | |)匹配foo或bar。

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

  f logFile | grep -vE'string one | string two'

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

  tail -f logFile | egrep -v'string one | string two'

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


I'm trying to use grep with -v for invert-match along with -e for regular expression. I'm having trouble getting the syntax right.

I'm trying something like

tail -f logFile | grep -ve "string one|string two"

If I do it this way it doesn't filter If I change it to

tail -f logFile | grep -ev "string one|string two"

I get

grep: string one|string two: No such file or directory

I have tried using () or quotes, but haven't been able to find anything that works.

How can I do this?

解决方案

The problem is that by default, you need to escape your |'s to get proper alternation. That is, grep interprets "foo|bar" as matching the literal string "foo|bar" only, whereas the pattern "foo\|bar" (with an escaped |) matches either "foo" or "bar".

To change this behavior, use the -E flag:

tail -f logFile | grep -vE 'string one|string two'

Alternatively, use egrep, which is equivalent to grep -E:

tail -f logFile | egrep -v 'string one|string two'

Also, the -e is optional, unless your pattern begins with a literal hyphen. grep automatically takes the first non-option argument as the pattern.

这篇关于使用正则表达式的grep过滤掉匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆