Reputation: 577
I have an information report in a text file, and I want to export them to CSV format and only for those lines that are in IPv4 format (by the first column). How do I do that in Perl?
10.10.10.1 10.10.11.11 51251 445 2019-03-05 11:59:29.008 29.156 ......
10.10.10.2 10.10.11.22 51234 123 2019-03-05 11:40:29.008 30.156 .A..SF
2001:288:8900:c400:2018:8ce:1ca8:9cb0 2404:6800:4012:1::200e 62105 443 2019-03-04 23:59:32.458 0.340 17 ...... 0 8 4763 1
2001:288:8001:c200:3171:3abcd:28af:7e8f 2404:6800:4008:c04::bc 50286 443 2019-03-04 23:59:32.471 0.000 6 .A.... 0 1 61 1
I only want to get the lines that are in IPv4 format as below,
10.10.10.1 10.10.11.11 51251 445 2019-03-05 11:59:29.008 29.156 ......
10.10.10.2 10.10.11.22 51234 123 2019-03-05 11:40:29.008 30.156 .A..SF
My code,
open my $fh, '<', 'in.txt';
open my $fo, '>', 'out.csv';
while (<$fh>) {
next if ($. == 1);
s/^\s+//;
my $text = (join ',', (split /\s+/, $_))."\n";
print $fo $text;
}
How do I test if the first column is in IPv4 format?
Upvotes: 0
Views: 114
Reputation: 241918
Regexp::Common contains the regex you need:
use feature qw{ say };
use Regexp::Common qw( net );
# ...
my @columns = split;
next unless $columns[0] =~ /$RE{net}{IPv4}/;
say {$fo} join ',', @columns;
Upvotes: 7
Reputation: 9231
Data::Validate::IP can also solve this specific task.
use strict;
use warnings;
use Data::Validate::IP 'is_ipv4';
...
next unless is_ipv4 $columns[0];
Upvotes: 2