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

时间:2016-09-17 02:11:32

标签: linux bash awk sed

我正在使用这个看起来像这样的数据文件:

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的所有行,因此输出将为:

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

我尝试使用sed '/hello/!d'但删除了该行。另外,我读到我可以在sed中使用!进行匹配,但我不确定如何匹配每一行并正确替换。如果你可以给我一些方向,我会非常感激。

4 个答案:

答案 0 :(得分:5)

awk救援!

$ awk '!/hello/{$0="match"}1' file

将不匹配“hello”的行替换为“match”并打印所有行。

答案 1 :(得分:5)

你可以这样做:

$ 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的行(您拥有该权限),然后替换将完整的模式空间(.*)替换为{{ 1}}。

答案 2 :(得分:3)

带有c(更改)命令的sed:

$ sed '/hello/!c match' file
match
hello random text in file
match
words in file hello
match
hello text in file can be
match

答案 3 :(得分:0)

只需使用awk即可获得清晰,简洁等等:

awk '{print (/hello/ ? $0 : "match")}' file
相关问题