小编Sis*_*nth的帖子

查找文件中所有出现的字符串,并在Perl中打印其行号

我有一个包含400000行的大文件,每行包含许多由tab分隔的关键字.

我还有一个文件,其中包含要匹配的关键字列表.说这个文件充当查找.

因此,对于查找表中的每个关键字,我需要在给定文件中搜索它的所有匹配项.并且应该打印出现的行号.

我试过这个

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

my $linenum = 0;

print "Enter the file path of lookup table:";
my $filepath1 = <>;

print "Enter the file path that contains keywords :";
my $filepath2 = <>;

open( FILE1, "< $filepath1" );
open FILE2, "< $filepath2" ;

open OUT, ">", "SampleLineNum.txt";

while( $line = <FILE1> )
{
    while( <FILE2> ) 
    {
        $linenum = $., last if(/$line/);
    }
    print OUT "$linenum ";
}

close FILE1;
Run Code Online (Sandbox Code Playgroud)

这将首次出现关键字.但我需要所有的发生,并且关键字应该完全匹配.

完全匹配面临的问题是,例如我有关键字"hello"和"hello world"

如果我需要匹配"hello",它返回包含"hello world"的行号,我的脚本也只能匹配"hello"并给出它的行号.

perl line-numbers string-matching

2
推荐指数
2
解决办法
2万
查看次数

标签 统计

line-numbers ×1

perl ×1

string-matching ×1