Ubuntu – Writing to /etc/networking/interfaces at boot using sed/awk

awkinterfacenetworkingsedUbuntu

Newbie here,

I'm trying to write to an auto-generated /etc/network/interfaces file of a newely provisioned XEN Ubuntu (12.04/10.04/8.04) DomU server at boot time using (currently) sed.

The auto-generated file is formatted as below:

auto eth0
iface eth0 inet static
    address 192.168.0.88
    gateway 192.168.0.254
    network 255.255.255.255
auto lo
iface lo inet loopback

Using sed, I'm trying to alter lines 1 & 2, add a third line, remove the gateway and last two lines, and add four extra lines at the end.

I'm currently stuck on adding the third line, as the script adds this line everytime it's run:

#!/bin/bash

sed -i "1s/.*/auto lo eth0/" /tmp/interfaces
sed -i "2s/.*/iface lo inet loopback/" /tmp/interfaces
sed -i "2a\iface eth0 inet static" /tmp/interfaces

Is it possible to add the third line only if it doesn't exist using sed (or awk)?

Likewise, how can I delete the gateway and last two lines only if they don't exist?

I'm new to sed, so am wondering whether I should be looking at awk instead for achieving this?

Any help would be greatly appreciated.

Colin.

EDIT: Just realised I should really ask this question over at StackOverflow

Best Answer

This will be easier using awk. Lets say you want to change

auto eth0
iface eth0 inet static
    address 192.168.0.88
    gateway 192.168.0.254
    network 255.255.255.255
auto lo
iface lo inet loopback

to

auto ServerFault-1
iface ServerFault-1 inet static
    address 1.2.3.4
    gateway 5.6.7.8
    network 255.255.255.255
auto lo
iface lo inet loopback

You can use following awk script

$ awk -f script.awk interfaces
auto ServerFault-1
iface ServerFault-1 inet static
address 1.2.3.4
gateway 5.6.7.8
network 255.255.255.255
auto lo
iface lo inet loopback
$
$ cat script.awk
{ 
  if ($0 ~ /auto eth0/) { print $1,"ServerFault-1" } \
  else if ($0 ~ /iface eth0/)                    { IFACE=$2; $2 ="ServerFault-1"; print $0} \
  else if (($0 ~ /address/) && (IFACE ~ /eth0/)) {print $1,"1.2.3.4"} \
  else if (($0 ~ /gateway/) && (IFACE ~ /eth0/)) {print $1,"5.6.7.8"} \
  else print $0
}
$
$ cat interfaces
auto eth0
iface eth0 inet static
address 192.168.0.88
gateway 192.168.0.254
network 255.255.255.255
auto lo
iface lo inet loopback
$