[英]Using a variable with a dollar sign in it in bash
I have a variable that contains a string with $ dollar signs in it and I want to use sed
to modify a text file. 我有一个变量,其中包含带有$美元符号的字符串,并且我想使用
sed
修改文本文件。 I get an error whenever there is a dollar sign in the variable but it works fine when there's no dollar sign. 每当变量中有美元符号时,我都会收到一个错误,但当没有美元符号时,它会正常工作。 How can I fix this?
我怎样才能解决这个问题? I am using multiple variables and literal text in one double quote.
我在一个双引号中使用了多个变量和文字文本。
The code: 编码:
sudo sed -i "textFile.txt" -e "s,\($var1\):\(.*:\):,\1:$var2WithDollarSign:$var3,g" textfile.txt
You have to backslash the special characters. 您必须反斜杠特殊字符。 It might be easier to switch to a more powerful tool, eg Perl, which already has functions to do that (
quotemeta
, s/\\Q$var\\E/.../
). 切换到功能更强大的工具(例如Perl)可能会更容易,该工具已经具有执行此功能的功能(
quotemeta
, s/\\Q$var\\E/.../
)。
I think your problem is that you're running sudo
to run the sed
command: 我认为您的问题是您正在运行
sudo
来运行sed
命令:
sudo sed -i "textFile.txt" -e "s,\($var1\):\(.*:\):,\1:$var2WithDollarSign:$var3,g" textfile.txt
The trouble is that the shell you're using process the arguments once, then the shell that sudo
runs on your behalf processes the arguments a second time. 问题在于您正在使用的shell处理一次参数,然后
sudo
代表您运行的shell第二次处理参数。 I recommend creating a shell script that contains the sed
command and sets the shell variables, and then run that from sudo
. 我建议创建一个包含
sed
命令的shell脚本并设置shell变量,然后从sudo
运行它。
cat > script <<!
sed -i "textFile.txt" -e 's,\($var1\):\(.*:\):,\1:$var2WithDollarSign:$var3,g' textfile.txt
!
sudo sh -x script
rm -f script
It will save a lot of brain-power. 它将节省大量的脑力。
$ cat xx.sh
var1='theperson'
var2WithDollarSign='the$voodoo$wizard'
var3='Albuquerque'
cat > script <<!
sed -i "textFile.txt" -e 's,\($var1\):\(.*:\):,\1:$var2WithDollarSign:$var3,g' textfile.txt
!
cat script
rm -f script
$ sh xx.sh
sed -i "textFile.txt" -e 's,\(theperson\):\(.*:\):,\1:the$voodoo$wizard:Albuquerque,g' textfile.txt
$
I've replaced su sh -x script
with cat script
. 我已将
su sh -x script
替换为cat script
。 You'd undo that substitution. 您可以撤消该替换。 The
-x
is optional; -x
是可选的; it just shows you what the script is executing. 它只是向您显示脚本正在执行什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.