http://www.perlmonks.org?node_id=98712


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