当找到与sed匹配时替换整行

时间:2013-05-08 12:12:08

标签: shell replace sed match

如果匹配模式,我需要用sed替换整行。 例如,如果该行是'一二二四四'并且如果'六'那么,那么整行应该被'fault'替换。

4 个答案:

答案 0 :(得分:60)

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

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

获取包含six的完整行,并将其替换为fault

示例:

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

它基于this solutionReplace whole line containing a string using Sed

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

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

  

如果我们有'一二六八一十三四'并且我们想要的话怎么办?   包括'八'和'十一'作为我们的“坏”字?

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

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

等等。

或者:

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

答案 1 :(得分:5)

以上答案对我来说很好,只是提到另一种方式

匹配单个模式并替换为新模式:

sed -i '/six/c fault' file

匹配多个模式并替换为新模式(连接命令):

sed -i -e '/one/c fault' -e '/six/c fault' file

答案 2 :(得分:3)

这可能适合你(GNU sed):

sed -e '/six/{c\fault' -e ';d}' file

或:

sed '/six/{c\fault'$'\n'';d}' file

答案 3 :(得分:2)

该行的内容

替换包含指定字符串的整行

文本文件:

Row: 0 last_time_contacted=0, display_name=Mozart, _id=100, phonebook_bucket_alt=2
Row: 1 last_time_contacted=0, display_name=Bach, _id=101, phonebook_bucket_alt=2

单个字符串:

$ sed 's/.* display_name=\([[:alpha:]]\+\).*/\1/'
output:
100
101

用空格分隔的多个字符串:

$ sed 's/.* display_name=\([[:alpha:]]\+\).* _id=\([[:digit:]]\+\).*/\1 \2/'
output:
Mozart 100
Bach 101

调整正则表达式以满足您的需求

[:alpha]和[:digit:] 是Character Classes and Bracket Expressions

相关问题