3

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?

Inian
  • 62,560
  • 7
  • 92
  • 110
Oliver Apel
  • 1,616
  • 2
  • 13
  • 28

1 Answers1

5

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'
Inian
  • 62,560
  • 7
  • 92
  • 110
  • this has not been working for me at all on el6 distros, using sed on the cli. im still plagued on this. `sed: -e expression #1, char x: unterminated `s' command` – blamb Feb 13 '19 at 06:28
  • 1
    @blamb: I verified this to be working. Please take caution on the usage of quotes and make sure you've set the `configProductName` variable with a proper value – Inian Feb 13 '19 at 06:36