如何用 sed 交换特定的单词: 考虑一行输入(在我的例子中是一条路径):
foo/bar/TEST/foo/bar/...
有平行路径:
foo/bar/PROD/foo/bar/...
我想根据原路径调换TEST和PROD
我的第一次尝试是:
sed -e "s#TEST#PROD#g" -e "s#TEST#PROD/g"
但不幸的是:
echo "foo/bar/PROD/foo/bar/..." | sed -e "s#TEST#PROD#g" -e "s#PROD#TEST#g"
result: foo/bar/TEST/foo/bar/...
按预期工作,但是
echo "foo/bar/TEST/foo/bar/..." | sed -e "s#TEST#PROD#g" -e "s#PROD#TEST#g"
result: foo/bar/TEST/foo/bar/...
两个替换都没有改变或更好。
我正在寻找一个选项,即在第一次替换成功时不执行第二次替换。
有什么想法或有更好的方法吗?
最佳答案
你可以使用 sed 的测试操作符
sed 's#TEST#PROD#g;t;s#PROD#TEST#g' file
t label
If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.
由于没有标签,因此如手册页摘录中所述,它将跳转到脚本的末尾,这意味着不再执行任何命令。
关于bash - sed 在单个命令中交换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746544/