Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract IP addresses from a text file using Perl?

Tags:

regex

perl

How do I extract just the IP addresses from a text file which has an IP address per line? I would like to extract the IPs and then list the IP addresses in a separate file. The text file that contains the IPs are in the following format:

Host somehost.com (192.168.1.1) is up (0.20s latency).
Host 10.1.0.0 is up (0.21s latency).
Host 172.1.0.0 is up (0.21s latency).


I'm trying to get the resulting text file to output as follows:

192.168.1.1
10.1.0.0
172.1.0.0

What is the best way to do this using Perl?

Note: It doesn't require an regular expression that account for valid IPs...just the IPs in the above format will do.

Thanks!

like image 406
qdog Avatar asked Jul 11 '10 03:07

qdog


1 Answers

use Regexp::Common qw/net/;
while (<>) {
  print $1, "\n" if /($RE{net}{IPv4})/;
}
like image 110
hobbs Avatar answered Oct 23 '22 13:10

hobbs