我在 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 之类的东西?
最佳答案
保留单引号在末尾,并在每个变量周围添加单引号。单引号防止 shell 折叠双反斜杠。额外的单引号将变量 refs 留在引号之外。
或者(别笑)考虑使用正斜杠。 Windows 将这两种斜杠识别为路径分隔符;只有 DOS 命令 shell 没有。
关于windows - 使用 sed 将 Windows 路径替换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43764493/