Skip to content
Advertisement

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

JavaScript

For e.g 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 ?

Advertisement

Answer

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,

JavaScript

This will match for any of the below input lines and modify it with the replacement part net.ipv4.ip_forward = 1

JavaScript

See the RegEx Demo for more clarity.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement