11

something strange is happening when trying to replace string with sed. This works :

find /home/loni/config -type f -exec sed -i 's/some_pattern/replacement/g' {} \;

So it works when I manually type the strings. But in the case below replacement doesn't occur :

find /home/loni/config -type f -exec sed -i 's/${PATTERN}/${REPLACEMENT}/g' {} \;

When I echo these two variables PATTERN and REPLACEMENT they have the correct values.

I'm trying to replace all occurences of pattern string with replacement string in all files in my config directory.

London
  • 14,986
  • 35
  • 106
  • 147

2 Answers2

29

Try

find /home/loni/config -type f -exec sed -i "s/${PATTERN}/${REPLACEMENT}/g" {} \;

instead. The ' quotes don't expand variables.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
  • and how about inside a bash command substition? `echo $(sed "s/local/$HOME/" /etc/hosts)` doesn't work. – gman Dec 31 '11 at 08:42
  • gman: That's because $HOME usually contains slashes, so after substitution, the whole command becomes `echo $(sed "s/local//home/erich/" /etc/hosts)` which will not work as expected. – Erich Kitzmueller Jan 01 '12 at 18:16
  • - This works for me. Use Double quote( " ) instead of single quote( ' ). – Manan Shah Nov 20 '18 at 07:13
3

Not sure if I got this right, but if you want to replace the ${PATTERN} with ${REPLACEMENT} literally you have to escape the dollar and maybe the braces, those are reserved characters in regular expressions:

find /home/loni/config -type f -exec sed -i -e 's/\$\{PATTERN\}/\$\{REPLACEMENT\}/g' {} \;
Bernhard
  • 8,583
  • 4
  • 41
  • 42