perl脚本比较两个文件的相同行和不同行

perl脚本比较两个文件的相同行和不同行,第1张

概述这个脚本diff.pl用于求两个文件相同的行和不同的行所构成的差集(即A中存在而B中不存在的行,及B中存在而A中不存在的行)。 #!/usr/bin/perl use 5.010; use strict; use warnings; use diagnostics;#warning info my ($fileA,$fileB) = @ARGV; open A,'<',$fileA or die

这个脚本diff.pl用于求两个文件相同的行和不同的行所构成的差集(即A中存在而B中不存在的行,及B中存在而A中不存在的行)。


#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use diagnostics;#warning info


my ($fileA,$fileB) = @ARGV;

open A,'<',$fileA or dIE "Unable to open file:$fileA:$!";
my %ta;
my $i; 
while(<A>){
  chomp;
  $ta{$_} = ++$i; 
}
close A;

open B,$fileB or dIE "Unable to open file:$fileB:$!";
#open COMM_AB,">$fileA.comm" or dIE "Unable to create comm file for $fileA and $fileB:$!";
open COMM_AB,">$fileA.comm.txt" or dIE "Unable to create comm file for $fileA and $fileB:$!";
my $countAB;
my @B; 
while(<B>){
    chomp;
    unless (defined $ta{$_}){
        push @B,$_;
    }else{
        $ta{$_} = 0;
        $countAB++;
        print COMM_AB $_ ."\n";
    }   
}
close B;
print "$countAB lines both in $fileA and $fileB\n";
close COMM_AB;


# Output diff to different files respectively
#open DIFF_A,">$fileA.diff" or dIE "Unable to create diff file for $fileA:$!";
open DIFF_A,">$fileA.diff.txt" or dIE "Unable to create diff file for $fileA:$!";
my $countA;
my %tt = reverse %ta;
foreach (sort keys %tt) {
    $countA += $_>0? print DIFF_A $tt{$_}."\n":0;
}

print "$countA lines in $fileA but not in $fileB\n";
close DIFF_A;


#open DIFF_B,">$fileB.diff" or dIE "Unable to create diff file for $fileB:$!";
open DIFF_B,">$fileB.diff.txt" or dIE "Unable to create diff file for $fileB:$!";
my $countB = scalar @B; 
print DIFF_B $_."\n" foreach @B; 
print "$countB lines in $fileB but not in $fileA\n";

if ($countA == 0 and $countB ==0 ){
    print STDOUT "The two files are IDentical\n";
}

close DIFF_B;


测试结果: 输入命令perl diff.pl test1.txt test2.txt

test1.txt:

slate
lava
granite
limestone
my ($fileA,$fileC) = @ARGV;

my ($fileA,$fileB) = @ARGV;
while(<A>){
  chomp;
  $ta{$_} = ++$i; 
}

text2.txt:

slate
lava
granite
limestone
open A,$fileA or dIE "Unable to open file:$fileA:$!";
while(<A>){
  chomp;
  $ta{$_} = ++$i; 
}

test1.txt.comm.txt:

slate
lava
granite
limestone
while(<A>){
  chomp;
  $ta{$_} = ++$i; 
}

test1.txt.diff.txt:

my ($fileA,$fileB) = @ARGV;


test2.txt.diff.txt:

open A,$fileA or dIE "Unable to open file:$fileA:$!";

总结

以上是内存溢出为你收集整理的perl脚本比较两个文件的相同行和不同行全部内容,希望文章能够帮你解决perl脚本比较两个文件的相同行和不同行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1278172.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-09
下一篇2022-06-09

发表评论

登录后才能评论

评论列表(0条)

    保存