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

by Agermain (Scribe)
on Jul 20, 2001 at 00:31 UTC ( #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 - Answer 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 meditating upon the Monastery: (3)
As of 2016-09-25 09:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (468 votes). Check out past polls.