Thursday, July 17, 2008

Match an IP range using egrep - bash


The input file:

$ cat myhosts.txt
172.22.21.123 mickwe
172.22.21.11 tests1
172.22.21.38 tests3
172.22.21.34 tests3
172.22.21.13 devenv3
172.22.21.9 dennet5
172.22.21.20 lic4
172.22.21.50 tests6

Required: Match IP range from 172.22.21.1 to 172.22.21.35 from the above file.

The solution using egrep is:

$ egrep '172\.22\.21\.([1-9]|(1[0-9]|2[0-2]|3[0-5])) ' myhosts.txt

Output:

172.22.21.11 tests1
172.22.21.34 tests3
172.22.21.13 devenv3
172.22.21.9 dennet5
172.22.21.20 lic4

2 comments:

Anonymous said...

Thank you. I would use a regular expression not only with egrep.

Unknown said...

egrep '([0-9]{1,3}\.){3}[0-9]{1,3}' /etc/hosts

© Jadu Saikia www.UNIXCL.com