Replace text in file with variable using sed
30,242
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
Related videos on Youtube
Author by
mcExchange
Updated on September 18, 2022Comments
-
mcExchange over 1 year
I need to replace a string in a file by another string which is stored in a variable.
Now I know thatsed -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 over 8 yearsTrue. However the answer given here by Oli is clearer and less cryptic.
-