Match a specific IP range

Hello all,

I would like a bit of help with a problem I am having. I have the following example file:

$ cat test_hosts
10.10.2.3 host1
10.10.2.4 host2
10.10.2.130 host3
10.10.2.5 host4
10.10.2.230 host5
10.10.2.22 host6

I need to match all IP addresses in the 10.10.2.1-10.10.2.22 range. I have tried all kind of things but for the life of me, I can't get it to work.

$ cat test_hosts | egrep "10\.10\.2\.[1,22]\s"

This shows nothing.

$ cat test_hosts | egrep "10\.10\.2\.[1,22]"
10.10.2.130 host3
10.10.2.230 host5
10.10.2.22 host6

Not exactly what I need. What am I doing wrong ?

Thanks,
Sylaan

sort -t "." -k 1,1n -k 2,2n -k 3,3n -k 4,4n infile| sed -n '/10.10.2.3 /,/10.10.2.22/p'

Sorry, that's not good as you have to specify an existing start and end, ie. .3 and .22. I have no better idea atm, but I bet someone will come up with a better code soon.

Your code doesn't work because [1,22] is not a range in regular expressions. Afaik it would be written [1-22] but I don't get it working either :slight_smile:

Yeah, forgot to mention that I tried the [1-22] and it didn't work for me either. I am on a SunOS 5.10.

The sort command works, thanks for that. Unfortunately I will have to eventually parse very large syslog files and I imagine that's not so efficient and fast :slight_smile:

Something like this:

egrep '10\.10\.2\.([1-9]|(1[0-9]|2[0-2])) ' test_hosts

That works, much thanks :slight_smile:

Yep, good to know, ty radoulov!