-1

我有两个文件

文件1.txt

123 abc
254 ded
256 ddw

文件2.txt

123
256

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

123  abc
256  ddw
4

3 回答 3

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)
于 2013-07-12T09:39:44.987 回答
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__
于 2013-07-12T10:33:20.897 回答
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";
}
于 2013-07-12T10:35:03.133 回答