15

I am trying to use sed to replace a line with spaces with a defined variable.

For example,

I want to replace 'a dumb string' with $lan, and lan="~/afile.py

I assumed the line would be

sed "s/a dumb string/$lan/g" file.txt

but this leave the 'a dumb string' part blank in the file.txt.

My problem seems simple enough. Any help is much appreciated.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
NPB
  • 434
  • 1
  • 3
  • 11

3 Answers3

20

I determined that because my @lan variable has slashes in it, I need to use the sed command using :

For example

sed "s:a dumb string:$lan:g" file.txt

This is probably a novice mistake, but I'm not that familiar with sed. Thank you for your help.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
NPB
  • 434
  • 1
  • 3
  • 11
18

sed is not aware that you're passing a variable -- it'll be interpreted as just another part of your regex. If your substitution contains slashes, the easiest thing to do is use an alternate separator char, like this:

sed "s|a dumb string|$lan|g" file.txt
FatalError
  • 52,695
  • 14
  • 99
  • 116
7

Sometime space in search string does not work so needed to use [[:space:]] in centos.

    sed -i 's/User[[:space:]]daemon/User apache/' httpd1.conf
Vidya Patil
  • 71
  • 1
  • 2