Home > Software engineering >  How to use variables in SED command (bash)
How to use variables in SED command (bash)

Time:02-21

I have these 3 sed commands:

sed -i '10,$s/-.*/-$LOWX:HIGHX $HIGHX]/' plot.p
sed -i '11,$s/ .*/ $HIGHY]/' plot.p
sed -i '14,$s/ .*/ $HIGHY/' plot.p

It is supposed to go to the line denoted by the first value (ie 10, 11, 14) and replace text following the character specified (ie -, ).

Currently, my sed command doesn't recognize the variables ($LOWX, $HIGHX, and $HIGHY), and it just makes the replacement with the literal "$LOWX" for example.

How can I get my sed command to recognize the variables within it?

I saw other answers to similar questions saying to use double quotes but that causes my sed command to be misinterpreted so that it cannot run.

My output:

set xr[LOWX-$LOWX:HIGHX $HIGHX]
set yr[0:HIGHY $HIGHY]
set ytics 0,1,HIGHY $HIGHY

Desired output:

set xr[LOWX-2:HIGHX 2]
set yr[0:HIGHY 1]
set ytics 0,1,HIGHY 1

CodePudding user response:

Does this give you your desired output?

sed -i "10,\$s/-.*/-$LOWX:HIGHX $HIGHX]/" plot.p
sed -i "11,\$s/ .*/ $HIGHY]/" plot.p
sed -i "14,\$s/ .*/ $HIGHY/" plot.p

CodePudding user response:

Single quotes will work. Take mine as a quick reference:

LAUNCH_APP="./xxx/launch-app.sh"
OLD_PROXY="xx-proxy.uds"
num=$(sed -n "/$OLD_PROXY/=" "$LAUNCH_APP")
sed -i ''${num}'s/^/#/' "$LAUNCH_APP"
  • Related