Probably this is what you need (note this will not work on Ubuntu 16.04):
#!/bin/bash
IFACE='eth0'
ifconfig | grep -A 7 "$IFACE" | sed -nr 's/^.*netmask\s([0-9\.]+)\s\sbroadcast.*$/\1/p'
In the first line the name of the network interface is assigned as value of the variable $IFACE
- this is useful for scripting, otherwise you can use grep -A 7 'eth0'
.
On the second line the output of the command ifconfig
will be piped to the grep
command, where the option -A 7
will output the following 7 lines after the line with the matched string/regexp. The output of that command will be piped to sed
.
Within the sed
command:
the regular expression ^.*netmask\s(.*)\s\sbroadcast.*$
will match to the whole line, from the beginning ^
to the end $
, that contains some characters .*
and the "keywords" netmask\space
, [0-9\.]+
and \s\sbroadcast
in that exact order;
that line will be substituted (s/old/new/
) with the content of the first capture group [(.*)
->\1
], where the regexp [0-9\.]+
will match to the strings that are consisted of digits end dots;
the option -r
(or -E
) will enable the extended regular expressions, which, in this case, will allow us to use the round brackets freely;
the option -n
with combination of the flag p
with output only the matched line and will preserve the rest output of sed
.
Here is an extended example that will parse the names of all network interfaces and will do similar as the above command for each of them:
for IFACE in $(ifconfig | sed -nr 's/(^[a-z0-9]+):.*/\1/p'); do \
echo -en "${IFACE}:\t"; ifconfig | \
grep -A 7 "$IFACE" | \
sed 's/ broadcast.*$//' | \
sed -rn 's/^.*netmask (.*)$/\1/p'; \
done
Sample output of the above command executed on a virtual machine with Ubuntu 18.04:
$ for IFACE in $(ifconfig | sed -nr 's/(^[a-z0-9]+):.*/\1/p'); do echo -en "${IFACE}:\t"; ifconfig | grep -A 7 "$IFACE" | sed 's/..broadcast.*$//' | sed -rn 's/^.*netmask (.*)$/\1/p'; done
ens33: 255.255.255.0
lo: 255.0.0.0