![当在一行中找到另一个字符串时,如何替换一个字符串?](https://linux22.com/image/143301/%E5%BD%93%E5%9C%A8%E4%B8%80%E8%A1%8C%E4%B8%AD%E6%89%BE%E5%88%B0%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%97%B6%EF%BC%8C%E5%A6%82%E4%BD%95%E6%9B%BF%E6%8D%A2%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%9F.png)
当在 unix 文件的一行中找到字符串“ny”时,我想将字符串“xy”替换为另一个字符串“ab”。
示例文本:
If we have xy today we can go to ny.
If we have xy tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.
输出文本应如下所示:-
If we have ab today we can go to ny.
If we have ab tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.
答案1
sed
可能是最简单的方法:
sed '/ny/s/xy/ab/g' file
它包含两个子命令:/ny/
搜索模式并s/xy/ab/g
进行实际替换。请注意,它将替换所有出现的xy
;如果您只想替换每行中的第一个,只需删除 final g
。
答案2
答案在awk
:
awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt
解释
/ny/
ny
:只有当有上线时才执行以下命令。gsub(/xy/,"ab")
: 仅在这些行上替换/xy/
为ab
, 。{print}
:无论您在哪一行,都打印该行。