28

How can I do this?

sed -i 's/wiki_host/$host_name/g' /root/bin/sync

It will replace wiki_host with the text $host_name. But I want to replace it with the content of the variable..

I tried it with

sed -i 's/wiki_host/${host_name}/g' /root/bin/sync

It doesn't work either.

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
Vince
  • 1,123
  • 3
  • 17
  • 31
  • check this: http://theunixshell.blogspot.com/2013/04/replace-string-in-file-with-value-in.html – Vijay Apr 30 '13 at 10:20

1 Answers1

56

You need to use double quotes:

$ sed -i "s/wiki_host/${host_name}/g" /root/bin/sync

Your single quotes prevent the shell variable from being replaced with its contents.

Andreas Fester
  • 34,015
  • 7
  • 86
  • 113
  • 3
    One important caveat is that the sed delimiter (`/` in this case) cannot be part of `${host_name}`, otherwise you will get errors. – wisbucky Mar 12 '18 at 05:51
  • In the last case you have to use other delimiters for sed, then it works with replacement value containing slashes as well. For example $ sed -i "s#wiki_host#${host_name}#g" /root/bin/sync – Kristjan Adojaan Apr 27 '20 at 14:26