我有一个包含复杂多行命令和一些无关文本的文件。我需要预先设置某些路径(例如,
/foo
)带前缀
/bar
。脚本可以运行多次,但不能在多个前加前缀
/酒吧
/bar/foo
,再次运行,然后
还
收到
/酒吧/美食
不
/bar/bar/foo
.
我必须使用
sed
与现有代码库保持一致。
我得出了预期的结果(如下),但我的方法似乎很麻烦。有没有更好(更短、更少重复)的方法?
$ echo '/foo' > infile
$ cat infile
"/foo" /foo
# Replace once, change expected:
$ sed -i '\#bar/foo#!s#\(/foo\)#/bar\1#g' infile
$ cat infile
"/bar/foo" /bar/foo
# Replace twice - no change expected:
$ sed -i '\#bar/foo#!s#\(/foo\)#/bar\1#g' infile
$ cat infile
"/bar/foo" /bar/foo
编辑:不要使用我的“解决方案”:它在一个重要的边缘情况下是错误的,请参阅下面的评论