Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searchin for a word in a text file?

Status
Not open for further replies.

patraf

Programmer
Sep 28, 2001
5
IE
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 &quot;The number of times the word $word appears is $count\n&quot;;
 
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 &quot;Can't open file: $!&quot;;
while ($line = <FILE>) 
    {
    while ($line =~ /$word/ig) { $count++; }
    }
close FILE;

print &quot;$count\n&quot;;

'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
See, I told you I was no good at Regex's. Thanks GoBoating.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top