简体   繁体   中英

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

#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

#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 ? 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=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.

What about removing all lines matching net.ipv4.ip_forward , no matter whether commented out or not and then appending what you need?

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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