[英]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: 现在,如果我有一个
var=172.31.0.0
,那么当我这样放置它时,如何在这种情况下使用它:
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.
任何帮助表示赞赏。
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. 当在带双引号的字符串中定义单引号时,请在
$var
周围加上单引号。
$ 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"
Following sed
command may help you in same. 遵循
sed
命令可能会帮助您。
sed "s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \3\4/" Input_file
OR in case you don't want 192 value in output then following may help: 或者,如果您不希望输出192的值,那么以下操作可能会有所帮助:
sed "s/;\([^ ]*\) \"\([^ ]*\) \([^ ]*\)\(.*\)/\1 \2 $var \4/" Input_file
Where variable var
has value as mentioned by you. 变量
var
具有您提到的值。 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). 另外,如果您对上述命令的结果感到满意,请使用
sed -i
命令将输出保存到Input_file本身(您在帖子中也使用过)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.