Casper
Casper

Reputation: 1723

How to use variables in sed with both single quote and double quote

I have this command, which creates a copy of a line and changes some substrings:

test file content before:

;push "route 192.168.20.0 255.255.255.0"

The working command:

sed -i -e '/;push "route 192.168.20.0 255.255.255.0"/ a push "route
172.31.0.0 255.255.0.0"' test

test file content after:

;push "route 192.168.20.0 255.255.255.0" 
push "route 172.31.0.0 255.255.0.0"

Now if I have a var=172.31.0.0, how can I use it in this scenario, when I put it like this:

sed -i -e '/;push "route 192.168.20.0 255.255.255.0"/ a push "route $var 255.255.0.0"' test

I got this:

;push "route 192.168.20.0 255.255.255.0" 
push "route $var 255.255.0.0"

I know single quotes make everything inside it literal string, now how can I use a variable here? Any help is appreciated.

Upvotes: 4

Views: 5971

Answers (2)

iamauser
iamauser

Reputation: 11489

Couple of different options.

Escape the "" around the string.

 \"route 192.68.20.0. 255.255.0\"

Example,

$ var="172.31.0.0"
$ echo ';push "route 192.168.20.0 255.255.255.0"' \
  | sed -e "/;push \"route 192.168.20.0 255.255.255.0\"/ a push \"route $var 255.255.0.0\""

;push "route 192.168.20.0 255.255.255.0"
push "route 172.31.0.0 255.255.0.0"

OR

Put single quotes around $var when they are defined inside a string with double quotes.

$ echo ';push "route 192.168.20.0 255.255.255.0"' \
  | sed -e '/;push "route 192.168.20.0 255.255.255.0"/ a push "route '$var' 255.255.0.0"'

;push "route 192.168.20.0 255.255.255.0"
push "route 172.31.0.0 255.255.0.0"

Upvotes: 6

RavinderSingh13
RavinderSingh13

Reputation: 133680

Following sed command may help you in same.

sed "s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \3\4/"   Input_file

OR in case you don't want 192 value in output then following may help:

sed "s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \4/"  Input_file

Where variable var has value as mentioned by you. In case you want to do these operations on a specific line which has some specific text then following may help you in same.

sed "/push/s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \3\4/"  Input_file

OR

sed "/push/s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \4/"  Input_file

Also if you are happy with above command's result then use sed -i command to save output to Input_file itself(which you had used in your post too).

Upvotes: 2

Related Questions