查找与正则表达式(正则表达式)不匹配的所有行 - “否定匹配”

时间:2017-05-19 09:32:28

标签: regex bash awk match

如何匹配匹配模式的所有内容?

尝试使用 sed 会产生非常难看的结果。

如果我们想要替换此文件:

The quick brown fox leaps over the lazy dog.  
The swift brown fox leaps over the lazy dog.  
The swift green frog leaps over the lazy fox.  
The quick yellow dog leaps over the lazy fox.  


用:

The quick brown fox jumps over the lazy dog.    
The swift brown fox jumps over the lazy dog.    
The quick yellow dog jumps over the lazy fox.    


这样做的优雅方式是什么?

4 个答案:

答案 0 :(得分:3)

您可以使用grep -Ev "regex pattern" /path/to/yout/file,它将匹配与正则表达式模式不匹配的每一行

答案 1 :(得分:3)

如果您只想打印与正则表达式不匹配的行,grep -v是该作业的正确工具。

你可以在不匹配的行上进行简单的替换:

sed -n '/frog/! s/leaps/jumps/ p' file

-n表示不打印,!否定匹配,s替换然后p打印

对于更复杂的处理,我使用awk(我在这里显示了与sed示例等效的内容):

awk '!/frog/ { sub(/leaps/, "jumps"); print }' file

答案 2 :(得分:1)

你正在寻找这样的东西吗?

awk '!/green/{$5="jump"; print}' file

The quick brown fox jump over the lazy dog.
The swift brown fox jump over the lazy dog.
The quick yellow dog jump over the lazy fox.

答案 3 :(得分:-3)

我建议使用awk。

您的数据保存在'input_file'中:

The quick brown fox leaps over the lazy dog.  
The swift brown fox leaps over the lazy dog.  
The swift green frog leaps over the lazy fox.  
The quick yellow dog leaps over the lazy fox.  


您希望匹配匹配 frog 的行。这是awk脚本。请注意,我们将 sed 正则表达式(正则表达式)放在字符串 cmd 中,将其替换为您想要的任何 sed 正则表达式(注意:您确实这样做)需要关闭(cmd)):

!/frog/  {cmd="echo " $0 "|sed 's/leaps/jumps/'" ;cmd|getline output;print output;close(cmd)}


将上面的内容放入脚本'match_all_but_frog.awk'中。然后:

awk -f match_all_but_frog.awk <input_file


输出:

The quick brown fox jumps over the lazy dog.  
The swift brown fox jumps over the lazy dog.  
The quick yellow dog jumps over the lazy fox.  



如果你想匹配'Frog','Frogs'或'FROGS'以及'frog':

BEGIN {
IGNORECASE = 1;
      }
!/frog|frogs/  {cmd="echo " $0 "|sed 's/leaps/jumps/'" ;cmd|getline output;print output;close(cmd)}
相关问题