使用sed将2个变量替换为一个变量位置以及正斜杠

时间:2022-07-13 17:06:30

i am trying to replace 2 variables with / in-between 2 variables but its giving sed expression -e error

我试图用2个变量替换2个变量,但是它给出了sed表达式-e error

 sed 's/'$presentnetwork'/'$netmask\/$subnet'/g' -i /etc/snmp/snmpd.conf

How to put the / and also substitute a variable using sed even if i try to put only one variable it is also not working

如何使用/并使用sed替换变量,即使我尝试只放置一个变量也不起作用

 sed 's/'$presentnetwork'/'$netmask\/'/g' -i /etc/snmp/snmpd.conf

Is it possible to use escape sequence and variable in the same sed command?

是否可以在同一个sed命令中使用转义序列和变量?

2 个解决方案

#1


2  

You need to wrap it with double quotes ":

你需要用双引号“包装它”:

sed "s/$presentnetwork/$netmask\//g" -i /etc/snmp/snmpd.conf
#   ^                              ^

Example:

$ cat a.html 
hello
$ a=hello
$ b=good
$ c=bye
$ sed "s/$a/$b\/$c/g" -i a.html 
$ cat a.html 
good/bye

#2


1  

sed isn't limited to / as delimiter, you can also use some other character to make escaping easier (if you know the character can't be part of your variable):

sed不限于/作为分隔符,你也可以使用其他一些字符来简化转义(如果你知道字符不能成为变量的一部分):

 sed "s_$presentnetwork_$netmask/_g" -i /etc/snmp/snmpd.conf

#1


2  

You need to wrap it with double quotes ":

你需要用双引号“包装它”:

sed "s/$presentnetwork/$netmask\//g" -i /etc/snmp/snmpd.conf
#   ^                              ^

Example:

$ cat a.html 
hello
$ a=hello
$ b=good
$ c=bye
$ sed "s/$a/$b\/$c/g" -i a.html 
$ cat a.html 
good/bye

#2


1  

sed isn't limited to / as delimiter, you can also use some other character to make escaping easier (if you know the character can't be part of your variable):

sed不限于/作为分隔符,你也可以使用其他一些字符来简化转义(如果你知道字符不能成为变量的一部分):

 sed "s_$presentnetwork_$netmask/_g" -i /etc/snmp/snmpd.conf