JohnnyFromBF
JohnnyFromBF

Reputation: 10191

Regex to match an IP adress within a colon and a slash with grep

The lines in the file I want to search look like this:

log:192.1.1.128/50098
log:192.1.1.11/22
...

Now I tried the following RegEx but none of them worked:

grep -oE "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" file
grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b"
grep -oE "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

Upvotes: 0

Views: 622

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You could use grep also.

$ grep -oP '.*?:\K[^/]*(?=/)' file
192.1.1.128
192.1.1.11

Grep's extended regexp parameter -E won't support \d, you need to use [0-9] instead of \d.

$ grep -oE "\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b" file
192.1.1.128
192.1.1.11

Upvotes: 2

Jotne
Jotne

Reputation: 41456

You can do this without regex using awk (on this simple example):

awk -F":|/" '{print $2}' file
192.1.1.128
192.1.1.11

To test if its IP contains three .:

awk -F":|/" '{n=split($2,a,".");if (n=4) print $2}' file
192.1.1.128
192.1.1.11

Upvotes: 3

Related Questions