sed not taking variable value

Hi All,
Could you please help me, why sed is not able to take variable value when I try to replace using sed.
I want to replace 2nd column (time) and keeping intact others.

cur="09:30"
CODE="VL"
new="09:35"

sed s/'\(.*def.monitor."${CODE}".qStart.*\)"${cur}"\(.*read\)/\1"${new}"\2'/g $FILE > /tmp/newFile

From

abcxx.def.monitor.VL.qStart         09:30               read

TO

abcxx.def.monitor.VL.qStart         09:35               read

so many quotes - so little time...

sed "s/\(.*def.monitor.${CODE}.qStart.*\)${cur}\(.*read\)/\1${new}\2/g" $FILE
1 Like

Wouldn't a better wording be "sed is not taking shell variable value when used in above setup"?
sed by its design / implementation is not meant to take shell variables (there's more suitable tools like awk or perl ), and even less so when used like posted in post#1:

  • Single quotes prevent shell expansion.
  • Single quotes within the parameters might confuse the tool AND users.
  • the entire "{script-only-if-no-other-script}" (c.f. man sed on linux Ubuntu 17.10) should be quoted - just to be on the safe side.

Would

sed "s/\(.*def.monitor.${CODE}.qStart.*\)${cur}\(.*read\)/\1${new}\2/g" file
abcxx.def.monitor.VL.qStart         09:35               read

come close to what you need?

1 Like

Thank you RudiC and Vgersh99. The sed is working as expected.
let me see if I can get the same results using awk .

I am not familiar with awk though. So tried sed therefore because I always need to replace the second column in the file.