Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

sed

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.

like image 779
Casper Avatar asked Oct 18 '25 14:10

Casper


2 Answers

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"
like image 188
iamauser Avatar answered Oct 21 '25 02:10

iamauser


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).

like image 45
RavinderSingh13 Avatar answered Oct 21 '25 02:10

RavinderSingh13