另外:包含BASH变量的sed表达式需要加双"
引号(),以正确解释该变量。
如果还对$ BASH变量加双引号(建议做法)
...然后您可以对变量双引号进行转义,如下所示:
sed -i "s/foo/bar ""$VARIABLE""/g" <file>
即,更换$变量相关"
用""
。
("$VAR"
将\"$VAR\"
结果简单地转义为带"
引号的输出字符串。)
例子
$ VAR='apples and bananas'
$ echo $VAR
apples and bananas
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' $VAR
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' "$VAR"
I like apples and bananas!
在这里,$ VAR"
在管道之前先被'
-"
引用(sed是-或-引用):
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g'
I like apples and bananas!
$ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g"
I like cherries!
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!
比较一下:
$ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g"
I like apples!
I like and!
I like bananas!
$ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g"
I like apples!
I like and!
I like bananas!
... 等等 ...
结论
作为标准做法,我的建议是
"
-quote BASH变量("$VAR"
)
"
-quote,再次声明那些变量(""$VAR""
),如果它们在sed表达式中使用(其本身必须-"
引用,而不是-'
引用)
$ VAR='apples and bananas'
$ echo "$VAR"
apples and bananas
$ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g"
I like cherries!