Rishi Rishi - 1 year ago 54
Bash Question

ignoring variable containing \ and multiple spaces usnig sed command

I have two variables,

first= new pool ser/@

i want to replace
with new pool
and also want to remove space before new word.

i have tried like,

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


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 Source

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/@" 
$ second=ESX_10.2.3.4@
$ sed -i "/${second}/ {s:${second}:${first//\\/\\\\}:g ; s/ new /new /}" mytestfile.txt