我有两个文件
文件1.txt
123 abc
254 ded
256 ddw
文件2.txt
123
256
输出(仅匹配 file1.txt 中的条目)
123 abc
256 ddw
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)
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__
我的 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";
}