1
${[a-zA-Z0-9._:]*}

I have used the above pattern for grepping words similar to ${SomeText}. How can I replace 'SomeText' with some other string i.e ${SomeText} --> SomeString in my bash script?

Example: file.txt

text text text ${SomeText1} text text ${SomeText2} text text text text text text
text text text text ${SomeText3} text text text text text text ${SomeText4} text
...

my script file:

SomeText1="foo"
SomeText2="bar"
..

I want to replace ${SomeText1} to $SomeText1 which will be replaced by foo. Similarly ${SomeText2} > $SomeText2 > bar

text text text foo text text bar text text text text text text
text text text text baz text text text text text text qux text
...
bin
  • 133
  • 1
  • 1
  • 10

2 Answers2

0

You can use sed

echo '${SomeText}, SomeText' | sed "s/\${SomeText}/\${SomeOtherText}/g"

will output

${SomeOtherText}, SomeText

if you need to use variables in sed, do it like this

a="SomeText"
b="SomeOtherText"

echo '${SomeText}, SomeText' | sed "s/\${$a}/\${$b}/g"

The output will be the same as above

EDIT: Better use arrays to store that strings

 SomeText[1]="foo"
 SomeText[2]="bar"

 i=0

 while [[ $i < $MAX_i ]]
 do
   ((i++))
   sed -i "s/\${SomeText[$i]}/${SomeText[$i]}/g"
 done

If you really need your approach, you will need double evaluation

 SomeText[1]="foo"
 SomeText[2]="bar"

 i=0

 while [[ $i < $MAX_i ]]
 do
   ((i++))
   toRepl="SomeText"$i
   scriptToCall=$(eval echo "s/\\\${$toRepl}/$`eval echo ${toRepl}`/g")
   sed -i $scriptToCall file
 done

So you iterate thru all indices (SomeText1, SomeText2, ...), save the current into var toRepl, evaluate the script you want to call, for i=1 it will be scriptToCall="s/\${SomeText[1]}/foo/g" cause you double evaluate toRepl -> ${SomeText1} -> foo and you pass that script to sed :)

Is it clear now?

bartimar
  • 3,374
  • 3
  • 30
  • 51
0

You can try this script:

while IFS='=' read k v; do
   v=$(tr -d '"' <<< $v)
   sed -i.bak "s/\${$k}/$v/g" file.txt
done < script
anubhava
  • 761,203
  • 64
  • 569
  • 643