tags:

views:

99

answers:

2

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!

+1  A: 
c-urchin
That will match all sorts of things that aren't valid IP addresses. Regexp::Common::net is much better. http://search.cpan.org/~abigail/Regexp-Common/lib/Regexp/Common/net.pm
friedo
The OP specifically said he didn't care whether they were valid ip addresses. What does "all sorts of things" mean? This matches 4 sets of dot-separated digits, which seems to me a fair characterization of what he was looking for.
c-urchin
This won't work if the IP address is at the start or end of the line.
Kinopiko
@Kinopiko. Very good point. I stand corrected. I should have used \b instead of \D. @friedo: Clearly using the Regexp library is better, if you know about it, or are going to be using it enough to make it worthwhile to find out about it.
c-urchin
+12  A: 
use Regexp::Common qw/net/;
while (<>) {
  print $1, "\n" if /($RE{net}{ipv4})/;
}
hobbs