bash 使用 grep 一次搜索两个表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15116460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:23:08  来源:igfitidea点击:

Search with grep for two expressions at once

bashgrep

提问by sup

This is basic but I am unable to google it. Can I use on invokation of grep to do

这是基本的,但我无法谷歌它。我可以在调用 grep 时使用它吗

grep expr1 | grep expr2

so that it prints lines including both expr1 and expr2?

以便它打印包含 expr1 和 expr2 的行?

采纳答案by twm

Try this:

尝试这个:

grep 'expr1.*expr2\|expr2.*expr1'

grep 'expr1.*expr2\|expr2.*expr1'

That's a little more complicated than it needs to be if you know that "expr2" will always come after "expr1". In that case, you could simplify it to:

如果您知道“expr2”总是在“expr1”之后,那么这比实际需要的要复杂一些。在这种情况下,您可以将其简化为:

grep 'expr1.*expr2'

grep 'expr1.*expr2'

回答by rounin

You can provide several expressions to search for with several -e flags. See also this post.

您可以提供多个表达式以使用多个-e 标志进行搜索。另见这篇文章

i.e.

IE

grep -e expr1 -e expr2

grep -e expr1 -e expr2

回答by NPE

What you have should work.

你所拥有的应该工作。

The following is an alternative way to achieve the same effect:

以下是实现相同效果的另一种方法:

grep -E 'expr1.*expr2|expr2.*expr1'

回答by user3728877

Actually your own suggestion is nearly correct if you want to get the lines that contain both expressions. Use:

实际上,如果您想获得包含两个表达式的行,您自己的建议几乎是正确的。用:

grep expr1 somefile | grep expr2