Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: 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 ( [id://98712]=note: print w/replies, xml ) Need Help??


in reply to how can i search a text file for a string and print every occurence of that string

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 Re: 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://98712]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2024-04-16 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found