1

i am trying to replace $old string with $new string in file where:

old=ESX_10.1.1.1\@11.11.11.11
new=host_15_11_0_111.static

I am using sed command:

sed i "s/${old}/${new}/g" /filename

but it does not replace the word and also not shows any error. I have tried it with many ways, like replacing:

sed i "s,${old},${new},g" /filename

and

sed i "s=${old}=${new}=g" /filename

but it does not work. Help me to solve this

John1024
  • 73,527
  • 11
  • 167
  • 163
Rockey
  • 11
  • 4
  • 1
    See [How to ensure that string interpolated into \`sed\` substitution escapes all metachars](http://unix.stackexchange.com/a/129063) – Stéphane Chazelas Jun 10 '16 at 06:22
  • 1. Did you really mean `sed i` or is that a typo for `sed -i`? 2. Did you have write access to `/` to create a temporary file and then rename it as `/filename`? – roaima Apr 19 '18 at 22:54

1 Answers1

1

You need to escape the \ with another \. You can do this in a bash shell variable as follows

sed -i -e "s/${old//\\/\\\\}/${new//\\/\\\\}/g" filename

See man bash Parameter Expansion for ${parameter/pattern/string}. We use the version with // instead of / to do it repeatedly. And we need to escape \ with itself, so it gets duplicated a lot.

meuh
  • 49,672
  • 2
  • 52
  • 114
  • `"s/${old//\\/\\\\}/${new}/g"` should work too as in this case `new` variable doesn't have backslashes to escape – Sundeep Jun 10 '16 at 06:26
  • Hi tried with s/${old//\\/\\\\}/${new}/g but it gives error,"sed: -e expression #1, char 2: unterminated `s' command" – Rockey Jun 13 '16 at 04:29
  • Note you must be using `bash` as your shell. You can add `set -x` to the start of the script so you can see what strings are actually being used. You must the double-quote char `"` as shown in the sed, and also when setting your variable `old="ESX_10.1.1.1\@11.11.11.11"`. – meuh Jun 13 '16 at 05:41