Perl:比较两个 CSV 文件并打印出差异 [英] Perl: Compare Two CSV Files and Print out differences
本文介绍了Perl:比较两个 CSV 文件并打印出差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Perl 的新手,我很难完成这项工作.我有两个单列 CSV 文件,我正在尝试将差异打印到第三个文件.
I'm a noob in Perl and I'm having a tough time getting this done. I have two single-columned CSV files, and I'm trying to print the differences to a third file.
File1:
123
124
125
126
File2:
123
124
127
Expected Output:
125
126
127
这是我到目前为止所得到的,但它不起作用:
This is what I've got so far, which isn't working:
#!/usr/bin/perl
use strict;
use warnings;
my $sheet_1;
my $sheet_2;
my $count1 = 0;
my $count2 = 0;
my $file1 = 'file1.csv';
my $file2 = 'file2.csv';
my $file_out = 'output.csv';
open (FILE1, "<$file1") or die "Couldn't open input file: $!";
open (FILE2, "<$file2") or die "Couldn't open input file: $!";
while( <FILE1> ) {
chomp;
$count1++;
#skip header;
next unless $count1;
my $row_1;
@$row_1 = split( /,/, $_ );
push @$sheet_1, $row_1;
}
@$sheet_1 = sort { $a->[0] <=> $b->[0] } @$sheet_1;
while( <FILE2> ) {
chomp;
$count2++;
#skip header;
next unless $count2;
my $row_2;
@$row_2 = split( /,/, $_ );
push @$sheet_2, $row_2;
}
@$sheet_2 = sort { $a->[0] <=> $b->[0] } @$sheet_2;
OUTER: {
foreach my $row_1 ( @$sheet_1 ) {
foreach my $row_2 ( @$sheet_2 ) {
if (@$row_1[0] eq @$row_2[0]){
last OUTER
}
else{
print "@$row_1[0]
";
}
}
}
}
close FILE1;
close FILE2;
推荐答案
可以使用Text::Diff Perl 模块来做到这一点.否则,请参见下文:
You can use the Text::Diff Perl module to do this. Otherwise, see below:
这是进行比较的一种算法.
Here's one algorithm to do the comparison.
use strict;
my @arr1;
my @arr2;
my $a;
open(FIL,"a.txt") or die("$!");
while (<FIL>)
{chomp; $a=$_; $a =~ s/[ ;, ]*//g; push @arr1, $a if ($a ne '');};
close(FIL);
open(FIL,"b.txt") or die("$!");
while (<FIL>)
{chomp; $a=$_; $a =~ s/[ ;, ]*//g; push @arr2, $a if ($a ne '');};
close(FIL);
my %arr1hash;
my %arr2hash;
my @diffarr;
foreach(@arr1) {$arr1hash{$_} = 1; }
foreach(@arr2) {$arr2hash{$_} = 1; }
foreach $a(@arr1)
{
if (not defined($arr2hash{$a}))
{
push @diffarr, $a;
}
}
foreach $a(@arr2)
{
if (not defined($arr1hash{$a}))
{
push @diffarr, $a;
}
}
print "Diff:
";
foreach $a(@diffarr)
{
print "$a
";
}
# You can print to a file instead, by: print FIL "$a
";
这篇关于Perl:比较两个 CSV 文件并打印出差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文