0

Wondering if someone might know a easy way to grep both the IP and IP in CIDR form in one go

Expected Output:

78.0.0.0/8

136.144.199.198

Current Output:

78.0.0.0

136.144.199.198

This is my current regex:

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\/[0-9]\{1,\}' 

This looked like it could work but seems to be only for perl

^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$
Riaan
  • 538
  • 1
  • 4
  • 14
  • Does this answer your question? [Regular expression that matches valid IPv6 addresses](https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses) – alecxs Aug 10 '20 at 11:33
  • 2
    @Riaan : You can turn on Perl style regexp with `-P`. – user1934428 Aug 10 '20 at 11:59
  • @user1934428 that looks like a plain old ERE to me which all greps support with `-E`, no need to use `-P` and make it experimental and GNU-specific. – Ed Morton Aug 10 '20 at 13:19
  • @EdMorton : I agree that we don't need `-P` here. I mentioned it because the OP expressed familiarity with Perl-Regexp in his question, so I thought he might prefer `-P` over `-E`. – user1934428 Aug 11 '20 at 06:00

1 Answers1

2

I see three ways:

Use -P option for perl regex:

grep -Po '([0-9]{1,3}\.){3}[0-9]{1,3}(/[1-2][0-9]|3[0-2]|[0-9])?' file

Same regex works fine also with -E option:

grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}(/[1-2][0-9]|3[0-2]|[0-9])?' file

Or escape all special characters:

grep -o '\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\(\/[1-2][0-9]\|3[0-2]\|[0-9]\)\?' file

All these commands give the same result:

78.0.0.0/8
136.144.199.198
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    That looks like a plain old ERE to me which all greps support with `-E`, no need to use `-P` and make it experimental and GNU-specific. – Ed Morton Aug 10 '20 at 13:19
  • 1
    @EdMorton: You're right, edited accordingly. I'm using *too much* Perl ;) – Toto Aug 10 '20 at 13:24
  • 1
    The single digit match should be pushed to the end of the three-part OR expression for the mask value since as it currently is, the match will end at the first digit found and not eg match 1.2.3.4/32, at least with GNU grep 3.7 in it's entirety and quit after seeing the 3 – Rondo Dec 15 '22 at 02:41
  • @Rondo: Good catch, updated accordingly. – Toto Dec 15 '22 at 09:12