我正在尝试编写Perl脚本来比较2个文件的内容,以便列出所看到的任何差异。尝试以下但我不确定如何继续下去。请注意,以下只是脚本的一部分,因为我事先已对2个文件的内容进行了排序。提前谢谢。
open (FILE1, "log") || die ("Can't open file log for reading") ;
open (FILE2, "master") || die ("Can't open file master for reading") ;
@file1 = <FILE1> ;
@file2 = <FILE2> ;
#$perlcompare = (compare('log','master')== 0) ;
#die ("Log and master files are equal and match.\n") ;
if (@file1 eq @file2) {
print "Log and master are equal and match.\n" ;
} else ????????????
exit 0;
答案 0 :(得分:5)
如果你需要留在Perl中,有File::Compare只会比较文件。
为了显示差异,有Text::Diff。
C:\Temp> cat file1 1 2 3 4 5
C:\Temp> cat file2 1 2 3 5
#!/usr/bin/env perl
use strict; use warnings;
use Text::Diff;
my $diffs = diff 'file1' => 'file2';
print $diffs;
C:\Temp> t --- file1 Fri Nov 18 00:01:40 2011 +++ file2 Fri Nov 18 00:01:49 2011 @@ -1,5 +1,4 @@ 1 2 3 -4 +5 -5
答案 1 :(得分:2)
如果你可以使用除perl以外的任何东西,我会推荐diff(1)或comm(1)
comm -3 sorted-file-1 sorted-file-2
答案 2 :(得分:1)
#!/usr/bin/perl
use strict;
use warnings;
use List::Compare;
open (my $log, "<", "log") or die $!;
open (my $master, "<", "master") or die $!;
my @content_log=<$log>;
my @content_master=<$master>;
my $lc = List::Compare->new(\@content_log, \@content_master);
my @intersection = $lc->get_intersection;
my @firstonly = $lc->get_unique;
my @secondonly = $lc->get_complement;
print "Common Items:\n"."@intersection"."\n";
print "Items Only in First List:\n"."@firstonly"."\n";
print "Items Only in Second List:\n"."@secondonly"."\n";
print "log\n", $lc->get_unique,"\n";
print "master\n", $lc->get_complement,"\n";
close $log;
close $master;