【问题标题】:Using sed to replace Windows path with numbers使用 sed 将 Windows 路径替换为数字
【发布时间】: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"'/'

标签: windows bash shell sed


【解决方案1】:

在末尾保留单引号,并在每个变量周围添加单引号。单引号可防止 shell 折叠您的双反斜杠。额外的单引号将变量 refs 留在引号之外。

或者(不要笑)考虑使用正斜杠。 Windows 将两种斜杠都识别为路径分隔符;只有 DOS 命令 shell 没有。

【讨论】:

  • 是的,米莎打败了我。我有同样的答案。试试这个: sed -i 's^C:\\path\\to\\'${OLD_VER}'^C:\\path\\to\\'${NEW_VER }'^g' test.txt
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 2012-01-11
  • 2011-01-24
  • 2012-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2021-12-18
相关资源
最近更新 更多