如果一行文字符合特定模式,我需要使用sed
替换整个行。例如,如果该行是'one two six three four',并且包含'six',则整行应更改为“fault”。
你可以使用以下任一方式完成:
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
更一般地,你可以使用表达式sed '/匹配/s/.*/替换/' 文件
。这将在包含匹配
的那些行中执行sed 's/匹配/替换/'
表达式。在你的情况下,这将是:
sed '/six/s/.*/fault/' file
如果我们有'one two six eight eleven three four'这些词语,而我们想要把'八(eight)'和'十一(eleven)'算作"坏词汇",怎么办呢?
在这种情况下,我们可以使用-e
来指定多个条件:
sed -e 's/.*six.*/fault/' -e 's/.*eight.*/fault/' file
等等,等等。
或者也可以:
sed '/eight/s/.*/XXXXX/; /eleven/s/.*/XXXX/' file
sed -i
命令。最好还要使用 sed -i.bak
命令,这样原始文件就会被替换,但也会备份到 file.bak
文件中。 - fedorqui/g
标志是无用的,因为一行上只能有一个匹配项,而且您只关心是否有一个或多个匹配项。 - tripleee.*
加上一些内容将会在每行中有一个唯一的匹配。谢谢! - fedorqui以上答案对我来说很好,只是提供另一种替代方法
匹配单个模式并用新模式替换:
sed -i '/six/c fault' file
匹配多个模式并用一个新的模式替换(连接命令):
sed -i -e '/one/c fault' -e '/six/c fault' file
用包含特定字符串的整行替换为该行内容
文本文件:
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:] 是字符类和方括号表达式
sed -e '/six/{c\fault' -e ';d}' file
或者:
sed '/six/{c\fault'$'\n'';d}' file
grep -v
吗? - user1252065