-1

How can I make regex to search for ipv4 address only. when I am doing

grep -E '([0-9]\.){1,3}[0-9]\b filename

It is showing group with five octets also.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Nikhil
  • 11
  • Do you want to extract matched substrings or the whole lines with the matching pattern? – Wiktor Stribiżew Sep 13 '18 at 11:20
  • 2
    Possible duplicate of [Validating IPv4 addresses with regexp](https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp) – blhsing Sep 13 '18 at 11:28
  • 1
    Try `grep -P '(?<!\d\.|\d)\d{1,3}(?:\.\d{1,3}){3}(?!\.?\d)' filename`. What a shame, none of the solutions in [Validating IPv4 addresses with regexp](https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp) work for the current scenario, though one of them is close. – Wiktor Stribiżew Sep 13 '18 at 11:30

1 Answers1

0

I doubt it can be done with a POSIX regex, thus I'd rather suggest a PCRE solution:

grep -P '(?<!\d\.|\d)\d{1,3}(?:\.\d{1,3}){3}(?!\.?\d)' filename

The pattern matches

  • (?<!\d\.|\d) - a location that is not immediately preceded with a digit and a dot or just a digit
  • \d{1,3} - 1 to 3 digits
  • (?:\.\d{1,3}){3} - three occurrences of
    • \. - a dot
    • \d{1,3} - 1 to 3 digits
  • (?!\.?\d) - a location that is not immediately followed with an optional dot and then a digit.

To make the pattern a bit more precises, replace the octet pattern (\d{1,3}) with (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563