Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Answer: how can i search a text file for a string and print every occurence of that string

by dkubb (Deacon)
on Jul 22, 2001 at 02:49 UTC ( #98712=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > how can i search a text file for a string and print every occurence of that string - Answer contributed by dkubb

This will match each occurence of a string inside a file:

#!/usr/bin/perl -w use strict; use IO::File; use constant FILE => 'search.txt'; use constant FIND => 'string to find'; IO::File->input_record_separator(FIND); my $fh = IO::File->new(FILE, O_RDONLY) or die 'Could not open file ', FILE, ": $!"; $fh->getline; #fast forward to the first match #print each occurence in the file print IO::File->input_record_separator while $fh->getline; $fh->close;

Explanation: The input record seperator, $/ has been set to your search string. When perl reads the file line by line, it actually is scanning the file until it finds the search string, printing the string each time it finds it. To my knowledge this is the fastest way to do brute force exact text matches in a file with pure perl.

  • Comment on Answer: how can i search a text file for a string and print every occurence of that string
  • Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2016-12-10 15:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (163 votes). Check out past polls.