Bash: Update a variable within a file

2020-05-03 12:57发布

问题:

I know this is a simple answer and I could probably keep digging around on Google before I stroll across the answer. But I am on a tight schedule and I was hoping for an easy response.

I need to update a variable in ifcfg-eth0 upon an installation. So in other words, this is what needs to happen:

The following variables need to change from:

ONBOOT=no
BOOTPROTO=dhcp

to

ONBOOT=yes
BOOTPROTO=static

Thanks in advance!

Cheers.

回答1:

sed -i -e '/^ONBOOT=/s|.*|ONBOOT=yes|; /^BOOTPROTO=/s|.*|BOOTPROTO=static|' file

Also try:

sed -i -re 's|^(ONBOOT=).*|\1yes|; s|^(BOOTPROTO=).*|\1static|' file

Or

sed -i -e 's|^\(ONBOOT=\).*|\1yes|; s|^\(BOOTPROTO=\).*|\1static|' file


回答2:

You can make use of something like this, which lets you define exactly what values you want to add in the file:

$ bootproto="static"
$ sed -r "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file
ONBOOT=no
BOOTPROTO=static

And to make the two of them together:

$ onboot="yes"
$ bootproto="static"
$ sed -r -e "s/(ONBOOT\s*=\s*).*/\1$onboot/" -e "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file
ONBOOT=yes
BOOTPROTO=static

Explanation

  • (BOOTPROTO\s*=\s*).* catches a group of text containing BOOTPROTO + any_number_of_spaces + = + any_number_of_spaces. Then, matches the rest of the text, that we want to remove. \1$var prints it back together with the given variable.
  • \s* keeps the current spaces as they were and then replaces the same line changing the current text with the bash variable $bootproto.
  • -r is used to catch groups with () instead of \( and \).

To make it edit in place, use sed -i.bak. This will create a backup of the file, file.bak, and the file will be updated with the new content.

All together:

sed -ir -e "s/(ONBOOT\s*=\s*).*/\1$onboot/" -e "s/(BOOTPROTO\s*=\s*).*/\1$bootproto/" file


回答3:

The similar as the sed solutons with perl

perl -i.bak -pe 's/(ONBOOT)=no/$1=yes/;s/(BOOTPROTO)=dhcp/$1=static/' files....