0

I am trying to replace a line in a file using sed and 2 variables. I tried this:

    varFind=$(echo "cfg_dir=/usr/local/.file1.cfg")
    varReplace=$(echo "cfg_dir=/usr/dir1/file2.cfg")

    sed -i "s/${varFind}/${varReplace}/" /usr/local/file.txt

But it keeps throwing this:

    user@localhost:~# ./script.sh sed: -e expression #1, char 17: unknown option to `s'

What am I doing wrong? I've looked and it appears to be right to me.

csimp
  • 3
  • 3
  • Add real string1 and string2 to your question. – Cyrus Aug 17 '15 at 21:59
  • 3
    The example you have works as expected @Cyrus assumes that there is a strange char in `varFind` of `varReplace`, '/' for example. – Victory Aug 17 '15 at 22:07
  • So if my variables were something like `varFind=$(echo "/usr/local/test.txt")` there would be issues? – csimp Aug 17 '15 at 22:09
  • 2
    Yes, `/` is used to separate the parameters for `s`. You can use another separator like `%` instead. – Sleafar Aug 17 '15 at 22:11
  • But what is the string in `varFind` is something like `cfg_dir=/usr/local`? How would I get around this issue? – csimp Aug 17 '15 at 22:13

1 Answers1

2

The simplest way to fix your problem is to change the separator for the s command. Change your sed command to this:

sed -i "s%${varFind}%${varReplace}%" /usr/local/file.txt

This works as long as your variables don't contain %.

Sleafar
  • 1,486
  • 8
  • 10
  • Thank you, I am still new to bash and it's taking me a little bit to get the hang of it. – csimp Aug 17 '15 at 22:19