How to make sed remove lines not matched by a substitution

淺唱寂寞╮ 提交于 2019-11-27 23:04:48

问题


I basically want to do this:

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

without having to write the expression twice:

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

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


回答1:


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

$ cat new.text 
A
B

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

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

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



回答2:


This might work for you:

sed '/<expression>/!d;s//<replacement>/g' file

Or

sed 's/<expression>/<replacement>/gp;d' file



回答3:


cat file | sed -n '/<expression>/{s//<replacement>/g;p;}'



回答4:


How about:

cat file | sed 'd/<expression>/'

Will delete matching patterns from the input. Of course, this is opposite of what you want, but maybe you can make an opposite regular expression?

Please not that I'm not completely sure of the syntax, only used it a couple of times some time ago.



来源:https://stackoverflow.com/questions/8225822/how-to-make-sed-remove-lines-not-matched-by-a-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!