perl scan files and do counting for regex expression matches

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • perhapscwk
    New Member
    • Sep 2007
    • 123

    perl scan files and do counting for regex expression matches

    i use below try to search from "search.txt " and find any string which match the regex expression i listed from file "keywords.t xt", however, it fail. if i put keywords like

    keyword1
    keyword2

    then it will works and display line number and keyword, but if use regex expression instead, it won't works. please help.

    actually i want to run the perl script and do a counting for number of matches for each regex expression but even the simple one i tried above not works.

    thanks.

    Code:
    open my $keywords,    '<', 'c:\perl\csv\keywords.txt' or die "Can't open keywords: $!";
    open my $search_file, '<', 'c:\perl\csv\search.txt'   or die "Can't open search file: $!";
    
    my $keyword_or = join '|', map {chomp;qr/\Q$_\E/} <$keywords>;
    #my $regex = qr|\b($keyword_or)\b|;
    #my $regex = qr/$keyword_or/;
    my $regex = qr|($keyword_or)|;
    
    
    while (<$search_file>)
    {
        while (/$regex/g)
        {
            print "$.: $1\n";
        }
    }
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    If I understood your question right, I am guessing the keywords in your keywords.txt will be something like:
    keywords.txt
    Code:
    keyword\d
    \d\d\d
    p\w{7}\d
    if that's the case, the line 5 of you code should be
    Code:
    my $keyword_or = join '|', map {chomp;qr/$_/} <$keywords>;

    Using \Q will escape all special characters that follow, which may not be what you want if you are trying to pass the regex from keyword.txt as is.

    Comment

    Working...