I try to replace some text within a text file. In my script I have store the text to find and to replace within two variables:
$currentProductName='hello'
$configProductName='byebye'
The replacing is done with this line:
sed -i'.bak' 's/$currentProductName/$configProductName/g' "$projectFile"
Everything works fine until any of my variables are containing whitespaces. If the $configProductName
is set to hello world
the sed
command does not work as expected.
I´ve already tried this but it doesn't work, too:
sed -i'.bak' 's/"$currentProductName"/"$configProductName"/g' "$projectFile"
sed -i'.bak' 's/\$currentProductName/\$configProductName/g' "$projectFile"
How do I must change the line to work as expected?
To preserve the spaces, you need to double-quote the variable and wrap it over once again with single quotes. This way you have control over which variables prefixed with $
needs to be expanded.
configProductName='hello world'
Use the sed
operation just as below and add the -i
flag once you find it working as expected.
sed 's/$currentProductName/'"$configProductName"'/g' file
hello world='hello'
$configProductName='byebye'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With