bash grep - 列出所有不包含这两种模式的行

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

grep - List all lines not containing both pattern

bashgrep

提问by Newbie

I have a text file having some records. I have two patterns to verify and I want to list all lines from the file not containing both pattern. How can I do this using grepcommand?
I tried few things using grep -vbut nothing seem to work.

我有一个包含一些记录的文本文件。我有两个模式要验证,我想列出文件中不包含这两个模式的所有行。如何使用grep命令执行此操作?
我尝试了几件事,grep -v但似乎没有任何效果。

Suppose my text file is as follows.
1. qwerpattern1yui
2. adspattern2asd
3. cczxczc
4. jkjkpattern2adsdapattern1

假设我的文本文件如下。
1. qwer pattern1yui
2. ads pattern2asd
3. cczxczc
4. pattern2jkjk adsdapattern1

I want to list lines 1, 2 and 3 only.

我只想列出第 1、2 和 3 行。

Thanks in advance.

提前致谢。

回答by anubhava

You can use:

您可以使用:

grep -w -v -e "word1" -e "word2" file

OR else using egrep:

或其他使用egrep

egrep -w -v -e "word1|word2" file

UPDATE:Based on comments, it seems following awk will work better:

更新:根据评论,似乎遵循 awk 会更好:

awk '!(/pattern1/ && /pattern2/)' file

回答by Digital Trauma

If I'm keeping up with the comments and edits right, I think this is what you need:

如果我跟上评论和编辑的权利,我认为这就是您所需要的:

$ grep -E -v 'pattern1.*pattern2|pattern2.*pattern1' test
1. qwerpattern1yui
2. adspattern2asd
3. cczxczc
$ 

回答by Jotne

If you like to try awk

如果你喜欢尝试 awk

awk '!/pattern1|pattern2/' file

It will not print any lines if it contains any of the patters

如果它包含任何模式,则不会打印任何行

You can also expand this:

你也可以扩展这个:

awk '!/pattern1|pattern2|pattern3|pattern4/' file


Example

例子

cat file
one
two
three
four
one two
two
nine
six two

remove all lines with oneor twoor both of them.

删除所有带有onetwo或两者的行。

awk '!/one|two/' file
three
four
nine

回答by Digital Trauma

While the standard tools-based answers (awk, grep, etc) are generally simpler and more straightforward, for completion if you needed a pure-bash solution, you could do this:

虽然基于标准工具的答案(awkgrep等)通常更简单、更直接,但如果您需要纯 bash 解决方案来完成,您可以这样做:

$ while IFS= read -r ln; do [[ $ln =~ pattern1 ]] && [[ $ln =~ pattern2 ]] && continue; printf "%s\n" "$ln"; done < test 
1. qwerpattern1yui
2. adspattern2asd
3. cczxczc
$