查找与正则表达式(regex)不匹配的所有行-“负匹配" [英] Find all lines that don't match a regular expression (regex) - a 'negative match'

查看:79
本文介绍了查找与正则表达式(regex)不匹配的所有行-“负匹配"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何匹配不匹配的所有内容?

尝试使用 sed 会产生非常尴尬的结果.

Trying with sed gives very awkward looking results.

如果我们要替换此文件:

If we want to replace this 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.  


与:


with:

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.    


做到这一点的优雅方法是什么?


What is an elegant way to do this?

推荐答案

如果只想打印与正则表达式不匹配的行,则 grep -v 是完成此任务的正确工具

If you just want to print lines that don't match your regular expression, grep -v is the correct tool for the job.

您可以在不匹配的行中用sed进行简单替换,如下所示:

You can do a simple replacement in sed on lines that don't match like this:

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

-n 表示不打印,取消匹配,用 s 代替,然后 p 打印

-n means don't print, ! negates the match, s substitutes then p prints

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

For more complex processing, I'd use awk (I've showed the equivalent to the sed example here):

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

这篇关于查找与正则表达式(regex)不匹配的所有行-“负匹配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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