快速替代grep -f

use*_*408 10 perl awk

file.contain.query.txt

ENST001

ENST002

ENST003
Run Code Online (Sandbox Code Playgroud)

file.to.search.in.txt

ENST001  90

ENST002  80

ENST004  50
Run Code Online (Sandbox Code Playgroud)

因为ENST003在第二个文件中没有条目且ENST004在第一个文件中没有条目,所以预期的输出是:

ENST001 90

ENST002 80
Run Code Online (Sandbox Code Playgroud)

要在特定文件中grep多查询,我们通常执行以下操作:

grep -f file.contain.query <file.to.search.in >output.file
Run Code Online (Sandbox Code Playgroud)

因为我在file.to.search中有10000个查询和几乎100000个原始文件,所以需要很长时间才能完成(比如5个小时).有没有grep -f的快速替代品?

Ale*_*lds 11

如果您需要纯Perl选项,请将查询文件键读入哈希表,然后根据这些键检查标准输入:

#!/usr/bin/env perl
use strict;
use warnings;

# build hash table of keys
my $keyring;
open KEYS, "< file.contain.query.txt";
while (<KEYS>) {
    chomp $_;
    $keyring->{$_} = 1;
}
close KEYS;

# look up key from each line of standard input
while (<STDIN>) {
    chomp $_;
    my ($key, $value) = split("\t", $_); # assuming search file is tab-delimited; replace delimiter as needed
    if (defined $keyring->{$key}) { print "$_\n"; }
}
Run Code Online (Sandbox Code Playgroud)

你会这样使用它:

lookup.pl < file.to.search.txt
Run Code Online (Sandbox Code Playgroud)

哈希表可以占用大量内存,但搜索速度要快得多(哈希表查找处于恒定时间内),这很方便,因为查找的密钥比存储密钥多10倍.

  • 这是法拉利与grep -f比较..谢谢 (2认同)

tri*_*eee 7

如果您有固定字符串,请使用grep -F -f.这比正则表达式搜索要快得多.


Mig*_*Prz 5

此Perl代码可以帮助您:

use strict;
open my $file1, "<", "file.contain.query.txt" or die $!;
open my $file2, "<", "file.to.search.in.txt" or die $!;

my %KEYS = ();
# Hash %KEYS marks the filtered keys by "file.contain.query.txt" file

while(my $line=<$file1>) {
    chomp $line;
    $KEYS{$line} = 1;
}

while(my $line=<$file2>) {
    if( $line =~ /(\w+)\s+(\d+)/ ) {
        print "$1 $2\n" if $KEYS{$1};
    }
}

close $file1;
close $file2;
Run Code Online (Sandbox Code Playgroud)