找到匹配项时用sed替换整行 [英] Replace whole line when match found with sed
问题描述
如果与模式匹配,我需要用sed
替换整行.
例如,如果该行是一二六三四",而如果存在六",则应将整个行替换为故障".
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
它将获取包含six
的完整行,并将其替换为fault
.
It gets the full line containing six
and replaces it with fault
.
示例:
$ cat file
six
asdf
one two six
one isix
boo
$ sed 's/.*six.*/fault/' file
fault
asdf
fault
fault
boo
它基于此解决方案到通常,您可以使用表达式 sed '/match/s/.*/replacement/' file
.这将在包含match
的那些行中执行sed 's/match/replacement/'
表达式.在您的情况下,这将是:
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?
在这种情况下,我们可以将-e
用于多个条件:
In this case we can use the -e
for multiple conditions:
sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' file
以此类推.
或者:
sed '/eight/s/.*/XXXXX/; /eleven/s/.*/XXXX/' file
这篇关于找到匹配项时用sed替换整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!