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

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

by davido (Cardinal)
on Oct 03, 2003 at 02:33 UTC ( [id://296143]=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

If the file is small enough that you don't mind a little slurping, here's an easy way using grep. (This assumes that you want to print the entire line where the matches are found):

my @list = grep /\btest\b/, <DATA>; chomp @list; print "$_\n" foreach @list; __DATA__ This is only a test. Here's a line that doesn't contain the trigger text. This line contains test and test again. Now you see it, now you don't. Testing one two three. Test or not to test?

This passes a filehandle to grep, along with a simple regexp that tells it to find only those lines that contain the word "test" (rejecting words like 'testing').

For matches across multiple lines you have to set the $/ special variable to paragraph or slurp mode and use an /s modifier on your regexp.

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-19 02:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found