仅在具有特定字符串的行中替换另一个字符串

-1 scripts text-processing

使用 Shell 脚本查找单词“here”的出现,并且仅在这些行中,将单词“this”替换为“that”。其余所有其他行都按原样打印。

Byt*_*der 6

假设你已经file.txt包含这两行:

here is this
but not this
Run Code Online (Sandbox Code Playgroud)

您可以运行以下sed命令在所有包含单词“here”的行上将“this”替换为“that”,而保持所有其他行不变:

sed '/\bhere\b/ s/\bthis\b/that/g' file.txt
Run Code Online (Sandbox Code Playgroud)

请注意,\b模式中的 表示单词边界,即单词的开头或结尾。如果没有这些,例如“那里”也会匹配。

输出:

here is that
but not this
Run Code Online (Sandbox Code Playgroud)

阅读man sed更多信息。