如何使 sed 删除与替换不匹配的行 [英] How to make sed remove lines not matched by a substitution

查看:83
本文介绍了如何使 sed 删除与替换不匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上想这样做:

cat file | grep '<expression>' | sed 's/<expression>/<replacement>/g'

不必写两次表达式:

cat file | sed 's/<expression>/<replacement>/g'

有没有办法告诉 sed 不要打印与替换命令中的正则表达式不匹配的行?

Is there a way to tell sed not to print lines that does not match the regular expression in the substitute command?

推荐答案

假设您有一个包含要替换的文本的文件.

Say you have a file which contains text you want to substitute.

$ cat new.text 
A
B

如果您想将 A 更改为 a 那么理想情况下我们会执行以下操作 -

If you want to change A to a then ideally we do the following -

$ sed 's/A/a/' new.text 
a
B

但是如果您不想得到不受替换影响的行,那么您可以使用 n 和 p 的组合,如下所示 -

But if you don't wish to get lines that are not affected with the substitution then you can use the combination of n and p like follows -

$ sed -n 's/A/a/p' new.text 
a

这篇关于如何使 sed 删除与替换不匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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