使用bash中的sed修改配置文件

时间:2017-05-17 07:50:28

标签: linux bash unix sed

我想在net.ipv4.ip_forward中将/etc/sysctl.conf设置为1.以下工作正常,但肯定会遗漏一些边缘情况

#Enable IP packet forwarding so that our VPN traffic can pass through.
sed -i 's/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf 
sed -i 's/#net.ipv4.ip_forward = 1/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf 
grep -qF "net.ipv4.ip_forward" /etc/sysctl.conf  || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf 

例如,如果sysctl.conf包含以下任何一项,则不匹配

#net.ipv4.ip_forward=1

##net.ipv4.ip_forward=1

是否有更可靠的方法来修改配置文件中的设置?

3 个答案:

答案 0 :(得分:4)

您可以使用-r开关在ERE中启用扩展正则表达式(GNU sed),并可选择将空格和#与{sed -ir 's/#{1,}?net.ipv4.ip_forward ?= ?(0|1)/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf 匹配3}},

net.ipv4.ip_forward = 1

这将匹配以下任何输入行,并使用替换部分net.ipv4.ip_forward=0 net.ipv4.ip_forward = 0 #net.ipv4.ip_forward=0 ##net.ipv4.ip_forward = 0 #net.ipv4.ip_forward=1 ##net.ipv4.ip_forward=1 #net.ipv4.ip_forward = 1 ##net.ipv4.ip_forward = 1

进行修改
{{1}}

有关更清晰的信息,请参阅regex ? optional item anchor

答案 1 :(得分:1)

如果删除与net.ipv4.ip_forward匹配的所有行,无论是否已注释掉,然后附加您需要的内容,该怎么办?

fgrep -v net.ipv4.ip_forward /etc/sysctl.conf > /etc/sysctl.conf.tmp
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf.tmp
mv /etc/sysctl.conf.tmp /etc/sysctl.conf

这很简单易读。

答案 2 :(得分:0)

您可以使用此设置为零个或多个空格以及零个或多个#(注释)

执行此操作
sed -i 's/[#| ]*net.ipv4.ip_forward[ ]*=[ ]*0/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf 
grep -qF "net.ipv4.ip_forward" /etc/sysctl.conf  || echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf