bash 使用 sed/awk 打印具有匹配模式或其他匹配模式的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5385234/
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 20:18:58  来源:igfitidea点击:

Using sed/awk to print lines with matching pattern OR another matching pattern

bashsedawk

提问by rick

I need to print lines in a file matching a pattern ORa different pattern using awkor sed. I feel like this is an easy task but I can't seem to find an answer. Any ideas?

我需要使用awksed在匹配模式不同模式的文件中打印行。我觉得这是一项简单的任务,但我似乎无法找到答案。有任何想法吗?

回答by SiegeX

The POSIX way

POSIX 方式

awk '/pattern1/ || /pattern2/{print}'

Edit

编辑

To be fair, I like lhf's way better via /pattern1|pattern2/since it requires less typing for the same outcome. However, I should point out that this template cannot be used for logical ANDoperations, for that you need to use my template which is /pattern1/ && /pattern2/

公平地说,我更喜欢lhf的方式,/pattern1|pattern2/因为它需要更少的输入来获得相同的结果。但是,我应该指出,此模板不能用于逻辑 AND运算,因为您需要使用我的模板/pattern1/ && /pattern2/

回答by Matthew Flaschen

Use:

用:

sed -nr '/patt1|patt2/p'

where patt1and patt2are the patterns. If you want them to match the whole line, use:

哪里patt1patt2是模式。如果您希望它们匹配整行,请使用:

sed -nr '/^(patt1|patt2)$/p'

You can drop the -rand add escapes:

您可以删除-r并添加转义符:

sed -n '/^\(patt1\|patt2\)$/p'

for POSIX compliance.

POSIX 合规性。

回答by Vijay

why dont you want to use grep?

你为什么不想使用grep?

grep -e 'pattern1' -e 'pattern2'

回答by lhf

awk '/PATT1|PATT2/ { print }'

awk '/PATT1|PATT2/ { print }'