I want to get the network address (192.168.42.) from my /etc/network/interfaces file. I am only interested for the interface "wlan0" and it would be good to have a check whether the section below exists.
In the example interfaces file of "wlan0" the IP adress is 192.168.42.1. For the init.d script I subsequently want to replace the last byte (*.1) with *.255. So the IP will should be: "192.168.42.255"
Does someone know how to read the address of the network from such a file for a init.d script and to replace the last byte?
iface wlan0 inet static
address 192.168.42.1
netmask 255.255.255.0
Currently, I just know how to check whether the file exists.
# Check for existence of needed config file and read it
test -r $CONFIGF || { echo "$CONFIGF not existing";
if [ "$1" = "stop" ]; then exit 0;
else exit 6; fi; }
I would use awk for this, since it is quite readable:
awk -v par="wlan0" '
/^iface/ && $2==par {f=1}
/^iface/ && $2!=par {f=0}
f && /^\s*address/ {print $2; f=0}' file
-v par="wlan0" provide the interface name you want to check/^iface/ && $2==par {f=1} if a line starts with iface and the 2nd value is the given interface name, set a flag./^iface/ && $2!=par {f=0} if a line starts with iface and the 2nd value is NOT the given interface name, unset the flag.f && /^\s*address/ {print $2; f=0} if the flag is set and a line starts with address, print the second black, being it the IP. Then, reset the counter (thanks Etan Reisner for the idea).Note this checks that the lines are not commented.
If you want to replace the last .1 with .255, you can replace the last condition to something like:
f && /^\s*address/ {ip=$2; sub(".1$", ".255", ip); print ip; f=0}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Given a file based on your input:
$ cat a
iface eth0 inet static
address xxx.xxx.xxx.xxx
netmask 255.255.255.0
iface wlan0 inet static
address 192.168.42.1
netmask 255.255.255.0
iface eth1 inet static
address yyy.yyy.yyy.yyy
netmask 255.255.255.0
It returns:
$ awk -v par="wlan0" '/^iface/ && $2==par {f=1} /^iface/ && $2!=par {f=0} f && /^\s*address/ {print $2; f=0}' a
192.168.42.1
And replacing the last portion of the ip:
$ awk -v par="wlan0" '/^iface/ && $2==par {f=1} /^iface/ && $2!=par {f=0} f && /^\s*address/ {ip=$2; sub(".1$", ".255", ip); print ip; f=0}' a
192.168.42.255
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With