Riaan
Riaan

Reputation: 608

Linux Grep or Sed Regular Expression for IP and optional CIDR

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]))?$

Upvotes: 0

Views: 861

Answers (1)

Toto
Toto

Reputation: 91488

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

Upvotes: 2

Related Questions