6

I need to replace a string in a file by another string which is stored in a variable.
Now I know that

sed -i 's|sourceString|destinationString|g' myTextFile.txt

replaces a string but what if destination String was a combination of a hard coded string and a variable?

myString="this/is_an?Example=String"
sed -i 's|sourceString|${myString}destinationString|g' myTextFile.txt

The latter doesn't work, since $myString is not interpreted as a variable.

mcExchange
  • 3,088

1 Answers1

10

Bash doesn't interpret variables in single-quote strings. That's why that isn't working.

myString="this/is_an?Example=String"
sed -i "s|sourceString|${myString}destinationString|g" myTextFile.txt

Would work.

Or if you need the single-quote for another reason, you can just butt strings together and they'll be intepreted as one:

myString="this/is_an?Example=String"
sed -i 's|sourceString|'"$myString"'destinationString|g' myTextFile.txt
Oli
  • 293,335