【问题标题】:Search a string in multiple files using Perl使用 Perl 在多个文件中搜索字符串
【发布时间】:2018-09-30 16:53:29
【问题描述】:

Perl 新手!!需要一些帮助 :) 我有 2 个文件,每个文件大小接近 500kb。

我需要在这些文件中搜索一组字符串(大约 800 个字符串),以检查文件 1、文件 2 中是否存在字符串,或者两者都存在或都不存在。

我知道的唯一选项是打开 file1,逐行读取并检查其中是否存在字符串,并对 file2 执行相同操作。 对近 800 个字符串(搜索字符串)做全过程似乎不好也不行。

有没有其他更有效的替代方法或使用 PERL 的单行代码?

【问题讨论】:

  • 对于像这样的小文件,您可以使用File::Slurper 将它们读入一个字符串,然后一口气在其中查找您的 800 个单词;每个文件搜索 800 次,而不是每个文件中的每一行搜索 800 次。
  • 文件有多大?而且,这 800 个字符串是普通的旧字符串,还是正则表达式?最后,在文件中,是否必须逐字查找字符串,或者是否存在空格(例如换行符)的差异?
  • 这两个文件每个大约 500kb 并且要搜索的所有字符串都是长度为 12 的纯字符串。当我们在这些文件中搜索这些字符串时,它们应该完全匹配并且不会有它们之间的任何空格。
  • 抱歉各位,我忘了说在搜索字符串时,我还需要记下找到字符串的行号。所以如果我使用上面提到的 File::Slurper 方法,我能得到行号吗?

标签: file perl search grep


【解决方案1】:

这是一个使用Regexp::Assemble 的示例。假设要匹配的字符串不跨越多行,它会为每行可以检查的所有字符串创建一个通用的正则表达式。因此,它只需要读取一次文件。

use feature qw(say);
use strict;
use warnings;
use Regexp::Assemble;

my @strings = qw(abc efg);  # <- Add more strings here

my $ra = Regexp::Assemble->new;
$ra->add( $_ ) for @strings;  # <- Creates a regexp that matches all the strings..
my $re = $ra->re;
my @files = qw(file1.txt file2.txt);  # <- Add more files if needed..
my @matches;
for my $file (@files) {
    push @matches, get_matches( $file, $re );
}
# Now post process the matches as you like..

sub get_matches {
    my ( $fn, $re ) = @_;

    my %matches;
    open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
    while (my $line = <$fh>) {
        while ( $line =~ /($re)/g ) {
            $matches{$1}++;
        }
    }
    close $fh;
    return \%matches;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 2010-12-03
    • 2011-04-28
    • 2014-10-30
    • 2012-05-17
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多