Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: traverse directory recursively and search for pattern

by rjt (Deacon)
on Mar 20, 2013 at 03:58 UTC ( #1024425=note: print w/ replies, xml ) Need Help??


in reply to traverse directory recursively and search for pattern

File::DirWalk makes the directory recursion easy. Perl's builtins trivialize the rest. The canonical way to use DirWalk is something like so:

#!/usr/bin/env perl use 5.014; use warnings; use File::DirWalk; # Process commandline arguments die "usage: $0 pattern path ..." if (@ARGV < 2); my $pattern = shift; # @ARGV now contains one or more paths to recurse # Set up DirWalk object with callback to grep each file my $dw = new File::DirWalk; $dw->onFile(sub { my $file = shift; if (-T $file) { open my $fh, '<', $file or die "Can't open $file: $!"; print map { "$file: $_" } grep { /$pattern/ } <$fh>; close $fh; } return File::DirWalk::SUCCESS; }); $dw->walk($_) for @ARGV;

The above gives you a very simple grep -R command. Probably more instructive than directly useful.

The -T operator is one of Perl's file test operators that evaluates to true if the file is an ASCII text file (based on some heuristic guesswork). There is an equivalent -B test for binary files.


Comment on Re: traverse directory recursively and search for pattern
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-09-18 06:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (108 votes), past polls