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

发布于 2024-12-17 15:53:21 字数 279 浏览 3 评论 0原文

我基本上想这样做:

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

而不必将表达式写两次:

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

合约呢 2024-12-24 15:53:21

假设您有一个文件,其中包含要替换的文本。

$ cat new.text 
A
B

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

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

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

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

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
梦一生花开无言 2024-12-24 15:53:21

这可能对你有用:

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

或者

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

This might work for you:

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

Or

sed 's/<expression>/<replacement>/gp;d' file
彩虹直至黑白 2024-12-24 15:53:21
cat file | sed -n '/<expression>/{s//<replacement>/g;p;}'
cat file | sed -n '/<expression>/{s//<replacement>/g;p;}'
夜巴黎 2024-12-24 15:53:21

怎么样:

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

将从输入中删除匹配的模式。当然,这与你想要的相反,但也许你可以制作一个相反的正则表达式?

请注意,我并不完全确定语法,前段时间只使用过几次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文