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
  • 498
  • 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

1

I see three ways:

Use -P option for perl regex:

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

Same regex works fine also with -E option:

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

Or escape all special characters:

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

All these commands give the same result:

78.0.0.0/8
136.144.199.198
Toto
  • 86,179
  • 61
  • 85
  • 118
  • 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