Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

( #98222=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 Agermain

Not sure what you mean by 'printing every occurrence of the string' - I'm guessing you mean print the string in context. The snippet below ought to work - replace 'string to search for' and 'searchfile.txt' with the obvious. It will show the first 25 characters on either side of the search string.

my $string = quotemeta 'string to search for'; my $slurp; { local $/ = undef; open my $textfile, '<', 'searchfile.txt' or die $!; $slurp = <$textfile>; close $textfile; } while( $slurp =~ m/ ( .{0,25} $string.{0,25} )gisx / ) { print "Found $1\n"; }

Comment on Answer: how can i search a text file for a string and print every occurence of that string
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 taking refuge in the Monastery: (6)
As of 2014-09-23 07:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (210 votes), past polls