Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use a regular expression on a text file

Status
Not open for further replies.

weloki

Technical User
Feb 19, 2004
12
US
Greetings, this is a newbie question: I need to know how to tell perl to use a regular expression on a text file and print the results. If I have a file "talk.txt" and I want to match all the strings, "abc" in that file, how do I tell perl to use the regexp on talk.txt? How would I get the all of those matches to be displayed? Thanks in advance.
 
Screw regex

grep is your answer

seek and find

--Paul
 
Thank you for your responses.

PaulTEG, Ok, how do I invoke grep on a Windows machine?

mikevh, where would I place the name of the talk.txt file that I need to search in?

 
like this:

open (FILE, &quot;<test.txt&quot;);
while (<FILE>) {
print if /abc/;
}
close FILE;

This will print all the text lines in test.txt that contain &quot;abc&quot;

D.

Masochist: Windows programmer with a smile.
 
grep is part of the POSIX toolset for windows, there is also a grep built on Borland's Turbo Pascal

Google'll find it

--Paul
 
From the command line:
Code:
perl -ne &quot;print if /abc/&quot; test.txt
This will print all the text lines in test.txt that contain &quot;abc&quot; (equivalent to typing &quot;grep abc test.txt&quot;)
 
grep &quot;abc&quot; test.txt
vs
perl -ne &quot;print if /abc/&quot; test.txt

grep is 15 keystrokes more economical
;P
 
&quot;grep is 15 keystrokes more economical&quot;

Indeed, so that leaves you with 15 keystrokes to play with getting grep to work on a Win32 machine!
 
15 keystrokes to get grep working... ambitious... :)

Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
If inside a script, you could try File::Grep [1].

Otherwise, you can try 'ppm install prep' and see if it can grep &quot;perl grep&quot; [2] off cpan (gets in close to your 15 characters [tongue]), else you'll need 'perl -MCPAN -e &quot;install prep&quot;' which loses your immidiate advantage. Repeat usage might bring an advantage, but I guess that's not the point, is it? :)

[1] [2]
________________________________________
Andrew - Perl Monkey
 
I want to express my gratitude for all of your replies, it really helped. It appears there are many ways to do one task. I now have a great head start on my projects, thanks to you all. 2thumbsup
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top