用 sed 找到匹配时替换整行 [英] Replace whole line when match found with sed

查看:138
本文介绍了用 sed 找到匹配时替换整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果匹配模式,我需要用 sed 替换整行.例如,如果该行是一二六三四",并且存在六",则应将整行替换为故障".

解决方案

您可以使用以下任一方法:

sed 's/.*six.*/fault/' file # 检查所有行sed '/six/s/.*/fault/' 文件 # 匹配的行 ->然后删除

它获取包含six的完整行并用fault替换它.

示例:

$ cat 文件六自卫队一二六一个 isix嘘$ sed 's/.*six.*/fault/' 文件过错自卫队过错过错嘘

它基于此解决方案使用 Sed 替换包含字符串的整行

更一般地,您可以使用表达式sed '/match/s/.*/replacement/' file.这将在包含 match 的那些行中执行 sed 's/match/replacement/' 表达式.在您的情况下,这将是:

sed '/six/s/.*/fault/' 文件

<小时><块引用>

如果我们有一二六八十一三四"并且我们想要包括八"和十一"作为我们的坏"词?

在这种情况下,我们可以将 -e 用于多个条件:

sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' 文件

等等.

或者:

sed '/8/s/.*/XXXXX/;/eleven/s/.*/XXXX/'文件

I need to replace the whole line with sed if it matches a pattern. For example if the line is 'one two six three four' and if 'six' is there, then the whole line should be replaced with 'fault'.

解决方案

You can do it with either of these:

sed 's/.*six.*/fault/' file     # check all lines
sed '/six/s/.*/fault/' file     # matched lines -> then remove

It gets the full line containing six and replaces it with fault.

Example:

$ cat file
six
asdf
one two six
one isix
boo
$ sed 's/.*six.*/fault/'  file
fault
asdf
fault
fault
boo

It is based on this solution to Replace whole line containing a string using Sed

More generally, you can use an expression sed '/match/s/.*/replacement/' file. This will perform the sed 's/match/replacement/' expression in those lines containing match. In your case this would be:

sed '/six/s/.*/fault/' file


What if we have 'one two six eight eleven three four' and we want to include 'eight' and 'eleven' as our "bad" words?

In this case we can use the -e for multiple conditions:

sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' file

and so on.

Or also:

sed '/eight/s/.*/XXXXX/; /eleven/s/.*/XXXX/' file

这篇关于用 sed 找到匹配时替换整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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