Perl脚本,用于比较两个文件并报告文件1中的新条目

时间:2014-05-27 17:42:13

标签: perl

我希望比较两个文件。来自具有IP的供应商的传入文件和我们一直使用的本地文件很快将使用供应商副本进行更新。我希望它只打印它发现的不在我们副本中的新数据。

IPV4-vendorlist.txt

10.0.0.0
192.168.1.1
192.168.2.2
192.168.3.3

IPV4-outgoing.txt

10.0.0.0
192.168.1.1
192.168.2.2

在这个例子中,我希望它打印"将添加以下内容:192.168.3.3"。

这是我到目前为止运行的代码,它只是没有产生任何输出:

use strict;

my $fname = 'IPV4-vendorlist.txt';

open my $vendor, "<", $fname
or die "Couldn't open $fname: $!";

my %urls;

while (my $url = <$vendor>) {
  chomp $url;
  $urls{$url} = undef;
}

close $vendor;
$fname = 'IPV4-outgoing.txt';

open my $ourfile, "<", $fname
or die "Couldn't open $fname: $!";

while (my $url = <$ourfile>) {
  chomp $url;
  next if exists $urls{$url}; 
  print "The following will be added: $url";
}

close $ourfile;

2 个答案:

答案 0 :(得分:1)

您的脚本(可能)有效。 “传出”列表中没有IP,这些IP也不在“供应商”列表中。 (也许你的意思是相反?“供应商”列表上的地址不在“传出”列表中。)

对于它的价值,标准的Unix工具如diffcmp以及comm已经提供了比较列表的基本功能。

答案 1 :(得分:0)

这种事情与List::Compare一样微不足道。将每个文件读入一个数组,其中每一行都是数组中的一个元素。然后:

use strict;
use warnings;

use List::Compare;
$lc = List::Compare->new(\@vendor_list, \@outgoing);
my @new_ips = $lc->get_unique();