Perl 如何从命令行中针对索引列根据字典文件筛选以制表符分隔的数据文件?

Perl 如何从命令行中针对索引列根据字典文件筛选以制表符分隔的数据文件?,perl,sed,awk,grep,Perl,Sed,Awk,Grep,我的文件file1包含 123 foo 45 bar 678 foobar ... xyz foo foobar ... 和file2包含 123 foo 45 bar 678 foobar ... xyz foo foobar ... 我想从file1获取一个只包含第二列的行的文件 出现在文件2中: 123 foo 678 foobar ... 这些列由选项卡分隔。我想把这个从 Mac OS X命令行(如果可能)。使用Perl: use strict; use warnings;

我的文件
file1
包含

123 foo
45  bar
678 foobar
...
xyz
foo
foobar
...
file2
包含

123 foo
45  bar
678 foobar
...
xyz
foo
foobar
...
我想从
file1
获取一个只包含第二列的行的文件 出现在
文件2中

123 foo
678 foobar
...
这些列由选项卡分隔。我想把这个从 Mac OS X命令行(如果可能)。

使用Perl:

use strict;
use warnings;

my %seen;
open (my $input2, "<", "input2") or die("open input2: $!");
while (<$input2>) { chomp; $seen{$_}++; }
close $input2;

open (my $input1, "<", "input1") or die("open input1: $!");
while (<$input1>) {
  chomp;
  my $key = (split (/\s+/))[1];
  print "$_\n" if $seen{$key};
}
close $input1;

下次你也可以发表你对这个问题的看法,并问一个更具体的问题。

这里有一种使用
awk
的方法:

awk -F "\t" 'FNR==NR { a[$0]++; next } $2 in a' file2 file1
结果:

123 foo
678 foobar
123 foo
678 foobar

试试这个:

grep -f file2 file1 > Output.txt
file1

123 foo
45  bar
678 foobar
文件2

xyz
foo
foobar
Output.txt


检查或以获取更多示例:

这绝对是
加入的作业

$ join -1 2 -2 1 <(sort file) <(sort file2)
foo 123
foobar 678

$join-12-21这里有一个用于读取文件的perl选项
map
用于使用“key”初始化哈希,并且正则表达式获取
grep
中使用的最后一列条目,如果该条目位于哈希中,则仅通过匹配行:

use strict;
use warnings;
use File::Slurp qw/read_file/;

my %keys = map { chomp; $_ => 1 } read_file 'file2.txt';
print for grep { /\t(.+)$/; $keys{$1} } read_file 'file1.txt';
数据集上的输出:

123 foo
678 foobar

为什么它需要先排序?
join
参数应该按排序顺序排列