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 append four extra lines at the very 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 sed -i "s/auto lo//g" /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?
You can do that with sed:
You can group commands with braces. The commands in the braces will only execute on the third line. The
iinsert command will only execute on the third line and if the third line doesn’t match the string between slashes (the!after it tells it to execute when it doesn’t match).You can do the same to delete:
Here we delete the third line only if it contains the string
gateway. You could probably be more generic and simply do:which will delete all lines that contain gateway, but maybe that’s not what you want.
As for deleting the last lines, the easiest solution would be:
Where the
ddelete command is executed on the last line if it matches eitherauto looriface lo inet loopback. Executing it twice will delete the last two lines if they match the patterns.If you want to add lines to the end of the file, you can do:
Or maybe only add them if the last line isn’t a specific line:
Hope this helps a little =)