Pro*_*mer 4 bash shell awk sed
test.csv 的内容是:
XYZ,IN123
Run Code Online (Sandbox Code Playgroud)
这是我的脚本:
Var1=IN123
Var2=A&B
sed -i "s/$Var1/$Var2/g" test.csv
Run Code Online (Sandbox Code Playgroud)
这是我替换test.csv内容的简单代码,当代码找到IN123时,将替换为A&B。
所以预期输出是:
XYZ,A&B
Run Code Online (Sandbox Code Playgroud)
但是通过上面的代码,我得到了:
XYZ,AIN123B
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Since the question asks about how this can be done with SED, there is a less known feature about it that can be very useful here - the delimiters can be whatever you want as long as they are not in your replacement string.
So for the above you could do
sed -i "s|$Var1|$Var2|g" test.csv
Run Code Online (Sandbox Code Playgroud)
..and can replace it with $ or : or anything else you like.
不幸的是,您被&
sed 替换字符串中具有特殊含义的事实所吸引。它是一个元字符,表示“匹配的整个模式”。为了获得字面的&符号,您必须对其进行转义:
Var1='IN123'
Var2='A\&B'
sed -i "s/$Var1/$Var2/g" test.csv
Run Code Online (Sandbox Code Playgroud)
单引号是必要的,以防止\&
被解释为赋值中的转义序列。我将它们添加到两个变量中以求对称。