0

In preparation for a re-IP of several servers I intend to search for all IP addresses on the servers which occur in settings files.

A simpleminded first attempt:

grep -e "[0-9]*\\.[0-9]*\\.[0-9]"

..produces false positives because strings with no digits is also allowed. Also, it finds version numbers like 1.2.3.4.5 which are not valid IP addresses.

I'm sure that someone has thought about this and come up with the perfect IP address finding regular expression grep that covers all exceptions.

Cameron
  • 96,106
  • 25
  • 196
  • 225
Stuart Woodward
  • 2,138
  • 4
  • 21
  • 31

1 Answers1

3

How about this:

(^|[^\.0-9])([0-2]?[0-9]{,2}\.){3}[0-2]?[0-9]{,2}($|[^\.0-9])

Run with -e "extended" grep. It won't match any numbers with more than four repeated groups, or that are greater than 299 (next best to excluding greater than 255).

Obviously, this only works for IPv4 adresses...

EDIT:

Building on this question's answer, here's a version that only matches valid IPv4 addresses (I modified it so it won't match numbers with more than four groups):

(^|[^\.0-9])(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($|[^\.0-9])
Community
  • 1
  • 1
Cameron
  • 96,106
  • 25
  • 196
  • 225