比较perl / python中的两个文件并打印匹配条目

时间:2013-07-12 09:33:39

标签: python perl

我有两个文件

FILE1.TXT

123 abc
254 ded
256 ddw

FILE2.TXT

123
256

输出(仅匹配file1.txt中的条目)

123  abc
256  ddw

3 个答案:

答案 0 :(得分:0)

Python解决方案。

import sys

with open('file1.txt') as f:
    d = {line.split()[0]: line for line in f if line.strip()}

with open('file2.txt') as f:
    sys.stdout.writelines(d.get(line.strip(), '') for line in f)

答案 1 :(得分:0)

Perl解决方案。

#!/usr/bin/perl

use strict;
use autodie;

my %d;
{
    open my $fh, "File2.txt";
    while(<$fh>) {
        chomp;
        $d{$_} = 1;
    }
}

{
    open my $fh, "File1.txt";
    while(<$fh>) {
        my($f1) = split /\s+/, $_; # or alternatively match with a regexp
        print $_ if $d{$f1};
    }
}

__END__

答案 2 :(得分:0)

我的Perl解决方案

#! /usr/bin/perl -w
use strict;
use warnings;


open FILE1, "File1.txt" || die "Cannot find File1.txt";
open FILE2, "File2.txt" || die "Cannot find File2.txt";

my %hash;

while (<FILE1>) {
    chomp;
    my ($key, $value) = split;

    $hash{$key} = $value;
}

while (<FILE2>) {
    chomp;
    my $key = $_;
    print "$key $hash{$key}\n";
}