Reputation: 2233
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.
Upvotes: 0
Views: 2594
Reputation: 63902
The similar as the sed
solutons with perl
perl -i.bak -pe 's/(ONBOOT)=no/$1=yes/;s/(BOOTPROTO)=dhcp/$1=static/' files....
Upvotes: 0
Reputation: 289555
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
(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
Upvotes: 3
Reputation: 75478
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
Upvotes: 5