perl比较两个文件并打印匹配的行 [英] perl compare two file and print the matching lines

查看:281
本文介绍了perl比较两个文件并打印匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个比较2个文件并打印比较结果的脚本.现在我想更改脚本而不是打印差异行,我想打印匹配的行.并计算每次运行脚本时匹配的时间.您能请任何一个给我个建议吗?谢谢!

I have this script which is compare 2 files and print out the diff result. now I want to change the script instead of print out the diff lines, i want to print the matching lines. and also to count how many time matched every time running the script. would you please any one can give me a suggestion. thanks!

#! /usr/local/bin/perl 
# compare 
my $f1 = "/opt/test.txt";
my $f2 = "/opt/test1.txt";
my $outfile = "/opt/final_result.txt";
my %results = (); 
open FILE1, "$f1" or die "Could not open file: $! \n";
while(my $line = <FILE1>){   $results{$line}=1;
}
close(FILE1); 
open FILE2, "$f2" or die "Could not open file: $! \n";
while(my $line =<FILE2>) {  
$results{$line}++;
}
close(FILE2);  
open (OUTFILE, ">$outfile") or die "Cannot open $outfile for writing \n";
foreach my $line (keys %results) { print OUTFILE $line if $results{$line} == 1;
}
close OUTFILE;

推荐答案

这不是做事的最干净方法...但是辛苦了.反转逻辑以使其打印所有unless $results{$line} == 1if $results{$line} != 1.

This isn't the cleanest way to do things... but the hard work has been done. Reverse the logic to make it print everything unless $results{$line} == 1, or if $results{$line} != 1.

要添加计数:

print OUTFILE "Count: $results{$line} - $line" if $results{$line} != 1;

或者,您可以使用grep过滤掉不需要的内容,完全避免使用if条件:

Alternatively, you could filter out the unwanted with a grep, avoiding the if condition totally:

foreach my $line ( grep { $results{$_} != 1 } keys %results ) {

    print OUTFILE "Count: $results{$line} - $line";
}

这篇关于perl比较两个文件并打印匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆