简体   繁体   中英

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. 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/.../ ).

I think your problem is that you're running sudo to run the sed command:

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. I recommend creating a shell script that contains the sed command and sets the shell variables, and then run that from 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.

Example

$ 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 . You'd undo that substitution. The -x is optional; it just shows you what the script is executing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM