Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

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

( #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 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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2014-12-21 18:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (106 votes), past polls