You should use the Stream EDitor sed
to do this.
sudo sed -i '/net\.ipv4\.ip_forward =/s/^#//' /etc/sysctl.conf
This command runs using sudo
, which is needed to edit /etc/sysctl.conf
. sudo
calls sed -i
which edits the files instead of printing the result to stdout. /net\.ipv4\.ip_forward =/
is a regex that looks for lines to modify, and s/^#//
removes #
only if it is the first character of the line.
One good practice when finding the right syntax for your edits is to not use sed -i
and instead just use sed
and view what comes out.
Also, if you want another safety net, you can run sed -i.bak
which will create a backup file with .bak
as the suffix. Be careful where you use that though, because the backup is created in the same dir as the original file, which can cause issues in various circumstances, such as when all the files in a directory are read, such as various .d
directories.
sed -i 's/^#\(net.ipv4.ip_forward.*\)/\1/' /etc/sysctl.conf
. Try it without the-i
first to see if it works as expected.net.ipv4.ip_forward = 1
.