2016-09-17 103 views
1

我与这个文件中的数据,看起来像这样的工作:替换所有行不包含匹配的字符串

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 

我试图替换做包含字符串的所有行hellomatch使用SED,所以输出会是:

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

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

回答

3

你可以这样说:

$ 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

+0

这完美的作品。谢谢你的协助。这是有道理的。如果你有一分钟​​的时间,请立即开通。 – DomainsFeatured

6

awk来救援!

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

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

+0

嘿Karakfa,这是好的,但删除除了其他线路更换线路。 – DomainsFeatured

+0

它不应该,'1'在那里打印所有行。 – karakfa

+0

啊,你是对的。谢谢。我用awk不太好,但是这个效果很好。 – DomainsFeatured

0

只需用awk为了清晰,简洁,等:

awk '{print (/hello/ ? $0 : "match")}' file 
3

桑达与c(其他城市)命令:

$ sed '/hello/!c match' file 
match 
hello random text in file 
match 
words in file hello 
match 
hello text in file can be 
match 
相关问题