2017-05-03 90 views
0

我在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的东西?

+0

太棒了!是的,它适用于末尾的单引号和变量名称周围的单引号。如果他们有单引号,我认为这些变量不会被翻译,而是作为文字字符串值。 – rziegler72

+0

通过添加单引号,您将结束变量前的引号字符串,并在之后再次启动它。你应该实际上双引号的变量,以避免分词:''s/xxx'“$ var1”'/ yyy'“$ var2”'/'' –

回答

1

在结尾保留单引号,并在每个变量周围添加单引号。单引号可防止shell折叠双反斜杠。多余的单引号将引用之外的变量引用留下。

或者(不要笑)考虑使用正斜杠。 Windows将这两种斜线识别为路径分隔符;它只是DOS命令外壳没有的。

+0

是的,米沙击败了我。我有同样的答案。试试这个:sed -i's^ C:\\ path \\ to \\'$ {OLD_VER}'^ C:\\ path \\ to \\'$ {NEW_VER}'^g'test 。文本 – Mark