【发布时间】:2017-05-03 15:37:54
【问题描述】:
我在 Windows 上使用 Git Bash shell,并尝试使用 sed 在 XML 文件中替换这样的字符串:
<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>
但是如果我需要为这些字符串传递变量,替换就不起作用了。
$ 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 之类的方法会更好吗?
【问题讨论】:
-
太棒了!是的,它在结尾处使用单引号并在变量名周围使用单引号。我不认为如果变量有单引号,它们会被翻译,而是作为文字字符串值。
-
通过添加单引号,您将在变量之前结束带引号的字符串并在之后重新开始。您实际上应该双引号该变量以避免分词:
's/xxx'"$var1"'/yyy'"$var2"'/'