Hi folks,
I am having problems in searching for a word in a text file. So once this word is found, I want to be able to count the number of times that this certain word is found. If you have any ideas it would be great,
Thanks Patrick.
Try this. My regex might be off, but this will get you going.
#!usr/bin/perl
$count = 0;
$word = "WordToSearchFor";
open (FILE, /path/to/file.ext) or die "Can't open file: $!";
while ($line = <FILE>)
{
if ($line = ~s/$word//ig)
{
$count++;
}
}
print "The number of times the word $word appears is $count\n";
A few minor tweaks....
- The 'if' on the regex would only do the first instance of a match in a line. If the word occurred in the line more than once, you'd miss all after the first one.
- Also, your regex is doing a replace which is not needed. You can just check for a match and increment $count on each match.
Code:
open (FILE, /path/to/file.ext) or die "Can't open file: $!";
while ($line = <FILE>)
{
while ($line =~ /$word/ig) { $count++; }
}
close FILE;
print "$count\n";
'hope this helps
If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.