使用 Shell 脚本查找单词“here”的出现,并且仅在这些行中,将单词“this”替换为“that”。其余所有其他行都按原样打印。
假设你已经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
更多信息。