0

I'm trying to replace a value shown as a variable with another value shown as a second variable, using the following line:

    sed -i "s/$header/$new/" file.f

Where "$header" is the old variable I want replaced with the new one ($new).

I'm getting this error:

    sed: -e expression #1, char 20: unknown option to `s'

I've tried

    sed -i 's/$header/$new/' file.f
    sed -i "s/$header/$new/" file.f
    sed -i 's/"$header"/"$new"/' file.f

None of it seem to work. How should I write this line so I can get the right output (replacing '$header' with '$new' on the file)?

Thanks in advance

  • What are values of both variables? – anubhava May 30 '17 at 17:10
  • As lurker mentioned, use `sed 's/\$header/\$new/'`. Also on a side note, O suggest to first test the `sed` command without `-i` and verify the output on screen. Once you are sure that it is working the way you expected, add `-i`. – Utsav May 30 '17 at 17:23
  • @lurker the variables are expanded before sed even starts, so that doesn't matter at all. – 123 May 30 '17 at 17:29
  • @Utsav I have no idea what you think your suggested code will do. – 123 May 30 '17 at 17:29
  • I tried your way and it works. Can you share what is your $header and $new? – Hungry Mind May 30 '17 at 17:30
  • 1
    @op, you'll have to show us the contents of the variables but at a guess they contain `/` and you will need a different delimiter. – 123 May 30 '17 at 17:31
  • 1
    Do you want to replace literally `$header` with `$new`, or the values of variables called `header` and `new`? – Benjamin W. May 30 '17 at 17:31
  • @123 - It would change $header with $new literally, which I think is what OP is trying to ask. – Utsav May 30 '17 at 17:33
  • @Utsav the title says variables and the first thing they tried `sed -i 's/$header/$new/'` would have worked if that were the case. You would only need to escape `$` if it were the last char. – 123 May 30 '17 at 17:35

2 Answers2

0
sed -i "s/$old/$new/" file

works fine. You can change the separtor if your data has the character /.

sed -i "s@$old@$new@" file
Baroudi Safwen
  • 803
  • 6
  • 17
0

If you are not sure of the content of the variables and to reduce clashing the separator you can use

sed "s^A$old^A$new^A"

to enter the CTRL-A press CTRL-V + CTRL-A (or any other value not expected in vars)

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134