What regular expression can I use to match an IP address?
With the following grep
syntax I want to match all IP address in a file (from a ksh
script)
grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' file
The problem: It also matches words (IP) that have more then 4 octets:
1.1.1.1.1
or
192.1.1.1.160
How can I match a valid IP and only IP addresses with 4 octets? I can also use Perl – a one line syntax solution, if grep
doesn't work.
Solution 1:
try this:
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts
which matches all expressions from 0.0.0.0
to 999.999.999.999
with
grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts
you will get IP addresses only
note:
on solaris probably egrep will do the job.
Solution 2:
How's this:
perl -MRegexp::Common=net -ne '/($RE{net}{IPv4})/ and print "$1\n"' /etc/hosts
Solution 3:
The
-w / --word-regexp
flag to grep
makes it only match on word boundaries, meaning that your match must either be surrounded by whitespace or begin / end at the beginning / end of the line!
Solution 4:
To only find matches with 4 octets exactly (excluding things like 1.1.1.1.1) use this:
grep -P '(?<=[^0-9.]|^)[1-9][0-9]{0,2}(\.([0-9]{0,3})){3}(?=[^0-9.]|$)'
It should never detect non-IP-addresses. The expression could be more complex to verify more things but this should work for most cases. It will not match a preceding 0 since 010.1.12.1 is not a common way to write IP addresses.
Solution 5:
if [ ` echo $ip | '^((25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)$' | grep -o "\." | wc -l` -eq 1 ];
then ipv4=true;
else
ipv4=false;