Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

Perl script to compare two files and report new entries in file 1

I am looking to compare two files. Incoming file from a vendor with IPs and a local file we have been using that will soon be updated with the vendor copy. I would like it it print only the new data that it finds that is not in our copy.

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

In this example, I would like it to print "The following will be added: 192.168.3.3".

Here is the code I have thus far that runs, it just doesn't produce any output:

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your script (probably) works. There are no IPs in the "outgoing" list which are not also already on the "vendor" list. (Perhaps you meant the other way around? There are addresses on the "vendor" list which are not on the "outgoing" list.)

For what it's worth, standard Unix tools like diff and cmp and comm already provide basic functionality for comparing lists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...