Reputation: 21
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?
Upvotes: 1
Views: 3150
Reputation: 11
This script do the job: https://github.com/JoeKuan/Network-Interfaces-Script
awk -f changeInterface.awk <interfaces file> <device=ethX>
<mode=(dhcp|static|manual)> [action=add|remove]
[address=<ip addr> netmask=<ip addr> <name=value> ...]
Upvotes: 1
Reputation: 5072
You can do that with sed:
sed -i -e '4{/iface eth0 inet static/! i\
iface eth0 inet static
}'
You can group commands with braces. The commands in the braces will only execute on the third line. The i
insert 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:
sed -i -e '3{/gateway/d}'
Here we delete the third line only if it contains the string gateway
. You could probably be more generic and simply do:
sed -i -e '/gateway/d'
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:
sed -i -e '${/auto lo/d;/iface lo inet loopback/d}'
sed -i -e '${/auto lo/d;/iface lo inet loopback/d}'
Where the d
delete command is executed on the last line if it matches either auto lo
or iface 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:
sed -i -e '$a\
newline1\
newline2\
newline3'
Or maybe only add them if the last line isn't a specific line:
sed -i -e '${/192\.168\.1\.1/!a\
newline1\
newline2\
newline3
}'
Hope this helps a little =)
Upvotes: 6