简体   繁体   中英

Replace string in bash script that contains dollar sign with a variable

I have a bash script that reads a file that contains strings and I want to do some variable substitution before executing the commands. It's pretty much what bash does itself. The user will provide an array of substitution arguments to the script. This seems pretty simple but I can't get the $ to be substituted in the string read from the file. Assume the STR is being read from a file and the ARGS are input to the script:

#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   #STR=`echo $STR | sed "s/'$'{$v}/$s/g"` #using this replaces nothing in STR
   STR=`echo $STR | sed "s/{$v}/$s/g"   #using this replaces the {number} correctly but leaves the $
   v=$((v+1))
done
echo $STR
# eval $STR

Running the above, gives: This is $what my input $string string looks like. $what? but I want the $ to not be there in the final STR.

#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   STR=`echo $STR | sed "s/\\${$v}/$s/g"`
   v=$((v+1))
done
echo $STR

This gets me this output, if I understood you correctly it is what you wanted.

This is what my input string string looks like. what?

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