替换所有不包含匹配字符串的行 [英] Replace All Lines That Do Not Contain Matched String

查看:102
本文介绍了替换所有不包含匹配字符串的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于替换所有不包含匹配字符串的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆