我在Windows上使用Git的Bash shell中,并试图在一个XML文件替换字符串像这样使用SED Windows路径:使用sed来取代数字
<customTag>C:\path\to\2016a.0</customTag>
像这样的字符串:
<customTag>C:\path\to\2017b.0</customTag>
我可以直接做替换这样的:
$ cat test.txt
<customTag>C:\path\to\2016a.0</customTag>
$ sed -i 's^<customTag>C:\\path\\to\\2016a.0</customTag>^<customTag>C:\\path\\to\\2017b.0</customTag>^g' test.txt
$ cat test.txt
<customTag>C:\path\to\2017b.0</customTag>
但是,如果我需要在变量传递的那些字符串,T他替换不起作用。
$ cat test.txt
<customTag>C:\path\to\2016a.0</customTag>
$ export OLD_VER=2016a.0
$ export NEW_VER=2017b.0
$ sed -i 's^<customTag>C:\\path\\to\\${OLD_VER}</customTag>^<customTag>C:\\path\\to\\${NEW_VER}</customTag>^g' test.txt
$ cat test.txt
<customTag>C:\path\to\2016a.0</customTag>
或者,如果我周围使用sed的表达双引号,我得到“无效后向引用”,大概是因为它认为,在今年的2是一个参考。
$ sed -i "s^<customTag>C:\\path\\to\\${OLD_VER}</customTag>^<customTag>C:\\path\\to\\${NEW_VER}</customTag>^g" test.txt
sed: -e expression #1, char 87: Invalid back reference
什么是正确的方式来逃避或引用这个,或者我会更好使用类似awk的东西?
太棒了!是的,它适用于末尾的单引号和变量名称周围的单引号。如果他们有单引号,我认为这些变量不会被翻译,而是作为文字字符串值。 – rziegler72
通过添加单引号,您将结束变量前的引号字符串,并在之后再次启动它。你应该实际上双引号的变量,以避免分词:''s/xxx'“$ var1”'/ yyy'“$ var2”'/'' –