Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
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 studying the Monastery: (12)
As of 2015-07-07 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (88 votes), past polls