替换所有不包含匹配字符串的行

问题描述:

我正在处理如下所示的数据文件:

I'm working with this file of data that looks like this:

text in file
hello random text in file
example text in file
words in file hello
more words in file
hello text in file can be
more text in file

我正在尝试使用sed将 not 包含字符串hello的所有行替换为match,因此输出为:

I'm trying to replace all lines that do not contain the string hello with match using sed, so the output would be:

match
hello random text in file
match
words in file hello
match
hello text in file can be
match

我尝试使用sed '/hello/!d',但这会删除该行.另外,我读到我可以在sed中使用!进行匹配,但是我不确定如何匹配每一行并正确替换.如果您能给我一些指导,我将不胜感激.

I tried using sed '/hello/!d' but that deletes the line. Also, I read that I can match using ! within sed but I'm not sure how to match every line and replace properly. If you could give me some direction, I would really appreciate it.

您可以这样做:

$ sed '/hello/!s/.*/match/' infile
match
hello random text in file
match
words in file hello
match
hello text in file can be
match

/hello/!确保我们仅在不包含hello的行(您拥有该权利)上进行替换,然后替换后用match替换完整的模式空间(.*).

/hello/! makes sure we're substituting only on lines not containing hello (you had that right), and the substitution then replaces the complete pattern space (.*) with match.