Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting IP address from a line from ifconfig output with grep

Tags:

regex

grep

Given this specific line pulled from ifconfig, in my case:

inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.255

How could one extract the 192.168.2.13 part (the local IP address), presumably with regex?

like image 445
JJJollyjim Avatar asked Jul 14 '12 10:07

JJJollyjim


People also ask

How do I use grep to find an IP address?

so you can use grep -oE "\b([0-9]{1,3}\.){ 3}[0-9]{1,3}\b" to grep the ip addresses from your output. Thanks. This works.

How do I get an IP address from Ifconfig?

use this one line script: ifconfig | grep "inet " | grep -v 127.0. 0.1|awk 'match($0, /([0-9]+\. [0-9]+\.


2 Answers

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

like image 88
Steve Avatar answered Sep 29 '22 07:09

Steve


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)

like image 40
burning_LEGION Avatar answered Sep 29 '22 07:09

burning_LEGION