Extracting IP address from a line from ifconfig output with grep

Here's one way using grep:

line='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"

Results:

192.168.2.13
192.168.2.256

If you wish to select only valid addresses, you can use:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Results:

192.168.0.255

Otherwise, just select the fields you want using awk, for example:

line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'

echo "$line" | awk -v OFS="\n" '{ print $2, $NF }'

Results:

192.168.0.255
192.168.2.256


Addendum:

Word boundaries: \b


Just to add some alternative way:

ip addr | grep -Po '(?!(inet 127.\d.\d.1))(inet \K(\d{1,3}\.){3}\d{1,3})' 

it will print out all the IPs but the localhost one.


use this regex ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?=\s*netmask)


you can use egrep (which is basically the same as grep -E)
in egrep there are named groups for character classes, e.g.: "digit"
(which makes the command longer in this case - but you get the point...)

another thing that is good to know is that you can use brackets to repeat a pattern

ifconfig | egrep '([0-9]{1,3}\.){3}[0-9]{1,3}'

or

ifconfig | egrep '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'


if you only care about the actual IP address use the parameter -o to limit output to the matched pattern instead of the whole line:

ifconfig | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'

...and if you don't want BCast addresses and such you may use this grep:

ifconfig | egrep -o 'addr:([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | egrep -o '[[:digit:]].*'

I assumed you were talking about IPv4 addresses only

Tags:

Regex

Grep