Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing text with sed containing whitespace in variable [duplicate]

Tags:

linux

bash

sed

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 sedcommand 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?

like image 948
Oliver Apel Avatar asked Oct 15 '25 03:10

Oliver Apel


1 Answers

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'
like image 179
Inian Avatar answered Oct 17 '25 16:10

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!