简体   繁体   English

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

[英]Modify config files with sed in bash

I am trying to set net.ipv4.ip_forward to 1 in /etc/sysctl.conf .The following works fine but it sure missing some edge cases 我试图在/etc/sysctl.conf中将net.ipv4.ip_forward设置为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 

For eg if the sysctl.conf contain any one of the following it won't match 例如,如果sysctl.conf包含以下任何一个,则它将不匹配

#net.ipv4.ip_forward=1

##net.ipv4.ip_forward=1 . ##net.ipv4.ip_forward=1

Is there a more reliable way to modify settings in config files ? 是否有更可靠的方法来修改配置文件中的设置?

You can use the -r switch to enable Extended Regular Expressions( ERE ) in GNU sed and optionally match the white-space and the # occurence with the regex ? 您可以使用-r开关来启用扩展正则表达式( ERE )在GNU sed和可选匹配空白和# occurence用正则表达式? optional item anchor , 可选项锚

sed -ir 's/#{1,}?net.ipv4.ip_forward ?= ?(0|1)/net.ipv4.ip_forward = 1/g' /etc/sysctl.conf

This will match for any of the below input lines and modify it with the replacement part net.ipv4.ip_forward = 1 这将匹配以下任何输入行,并使用替换部件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

See the RegEx Demo for more clarity. 有关更清晰的信息,请参阅RegEx演示

What about removing all lines matching net.ipv4.ip_forward , no matter whether commented out or not and then appending what you need? 删除匹配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

This is simple and readable. 这很简单易读。

You can use this setting to do it for zero or more spaces and zero or multiple #(comment) 您可以使用此设置为零个或多个空格以及零个或多个#(注释)执行此操作

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM