如何使sed删除与替换不匹配的行?

时间:2021-06-07 16:51:04

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?

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

4 个解决方案

#1


22  

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 -

如果你想把A换成A,那么理想情况下我们要做的是-

$ 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 -

但是如果你不希望得到不受替换影响的线,那么你可以使用n和p的组合

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

#2


15  

This might work for you:

这可能对你有用:

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

Or

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

#3


4  

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

#4


-1  

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.

请不要说我对语法不太确定,只是在不久前才用过几次。

#1


22  

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 -

如果你想把A换成A,那么理想情况下我们要做的是-

$ 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 -

但是如果你不希望得到不受替换影响的线,那么你可以使用n和p的组合

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

#2


15  

This might work for you:

这可能对你有用:

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

Or

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

#3


4  

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

#4


-1  

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.

请不要说我对语法不太确定,只是在不久前才用过几次。