windows - 使用 sed 将 Windows 路径替换为数字

标签 windows bash shell sed

我在 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/

相关文章:

c# - 如何在批处理文件或 C# 中等待任务计划程序任务完成?

ruby-on-rails - rake 中止!没有要加载的文件 -- 赶紧

bash - Amazon 中支持 VPC 的可用性区域

bash - 剪切并替换 bash

windows - 适用于 Windows 的 CouchDB - SSL 证书 - 连接错误

windows - 跨机器 UI 自动化框架?

regex - grep:如何使用非捕获组?

bash - 从命令行在目录中查找文件

bash - POSIX 兼容的 shell 相当于 Bash "while read -d $'\0' ..."?

string - bash 字符串比较