【发布时间】:2012-12-06 10:42:28
【问题描述】:
我有一个包含 400000 行的大文件,每行包含许多由制表符分隔的关键字。
而且我还有一个文件,其中包含要匹配的关键字列表。说这个文件充当查找。
因此,对于查找表中的每个关键字,我需要在给定文件中搜索所有出现的关键字。并且应该打印出现的行号。
我试过了
#!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;
这给出了关键字的第一次出现。但我需要所有的出现,并且关键字应该完全匹配。
完全匹配面临的问题是,例如我有关键字“hello”和“hello world”
如果我需要匹配“hello”,它也会返回包含“hello world”的行号 我的脚本应该只匹配“hello”并给出它的行号。
【问题讨论】:
-
简单:如果效率不是一个大问题,您可以将所有关键字从 file2 加载到一个数组中。然后遍历 file1 并在每一行搜索数组中的所有关键字。
-
你能详细说明最后一段吗?是否要搜索“hello”以返回“hello world”?
-
@KarthikT 如果我搜索 hello world 它应该只匹配那个词而不是它的子字符串,比如 hello 。
标签: perl string-matching line-numbers