Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: How to search string in all files in directory

by swampyankee (Parson)
on Dec 10, 2008 at 14:28 UTC ( [id://729423]=note: print w/replies, xml ) Need Help??


in reply to How to search string in all files in directory

The first place to look is glob, since it appears that you don't want to recurse down a directory tree. As an example (NOT TESTED)

# insert appropriate shebang line use strict; use warnings; my @files = glob("chat/*.htm"); # use something like [Hh][Tt][Mm] if y +ou're unsure about the case @files = grep { -s $_ and -f _ and -r _} @list; print "Enter search string :"; my $string = <>; # read from STDIN chomp($string); # strip off the line feed resulting from <enter> my $quoted_string = quotemeta($string); # quote all meta-characters. + Remove if not needed foreach my $file (@files) { my $filehandle; unless(open($filehandle, "<", $file)) { warn "Could not open $file because $!\n"; next; } my @contents = <$filehandle>; # presuming the files are not too la +rge chomp(@contents); close($filehandle) or die "Could't close $file because $!\n"; @contents = grep { /$quoted_string/ } @contents; if(@contents){ print "$string was found in $file:\n\t",join("\n\t",@contents), +"\n"; } }
Warning! Code is NOT tested, and I won't even guarantee it will compile.

Doubtless there are better ways to do this than my example. One obvious improvement could be to slurp up the entire file into a scalar, not read it into an array, by setting $/ to undef; this is probably faster. Other improvements would be to permit regex.


Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://729423]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-20 04:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found