Rishi Rishi - 5 months ago 7
Bash Question

ignoring variable containing \ and multiple spaces usnig sed command

I have two variables,

first= new pool ser/@10.25.89.322
second=ESX_10.2.3.4@10.52.33.21


i want to replace
ESX_10.2.3.4@10.52.33.21
with new pool
ser/@10.25.89.322
and also want to remove space before new word.

i have tried like,

sed -i -e "s/${second}/"${first//\\/\\\\}"/g"


and

sed -i -e "s/${second}/"${first//\\[ ]*/\\\\}"/g"
sed -i -e "s/${second}/"${first//\\ */ *\\\\}"/g"


I don't want to delete space ,just want to replace as it is(except space before "new").

Answer

Give a try to this:

sed -i "/${second}/ {s:${second}:${first//\\/\\\\}:g ; s/ new /new /}"

It is removing the space in the first occurrence of new in the line after replacement.

Also, in the test below, double-quote were added:

$ first=" new pool ser/@10.25.89.322" 
$ second=ESX_10.2.3.4@10.52.33.21
$ sed -i "/${second}/ {s:${second}:${first//\\/\\\\}:g ; s/ new /new /}" mytestfile.txt
Comments