http://qs321.pair.com?node_id=1224235


in reply to Loop through all directory and files and lines

Hi, here is a script I use often to search thru my files, it's not the best code, but it works. Notice the commented out lines which skip binary files. Usually, you don't want to search a binary file.
#!/usr/bin/perl use warnings; use strict; use File::Find; $|++; # defaults are case-insensitive, no recurse, open and search files (no +t filename) if ($#ARGV < 0){die "Usage zgrep 'pattern' c(case sensitive optional) +r(recurse optional) n(search name only optional) examples: zgrep 'debug me' r will recursively search all files for 'debug me'\n"; } my ($recurse, $name, $case) =(0,0,0); if( grep{/\bn\b/} @ARGV ){@ARGV = grep { $_ ne 'n' } @ARGV; $name = 1 +}; if( grep{/\br\b/} @ARGV ){@ARGV = grep { $_ ne 'r' } @ARGV; $recurse = + 1 }; if( grep{/\bc\b/} @ARGV ){@ARGV = grep { $_ ne 'c' } @ARGV; $case = 1 +}; #print "$name $recurse $case @ARGV\n"; my $path = '.'; #only accept 1 search string, so quote phrases my $search = $ARGV[0]; my $regex; #defaults to case insensitive if ($case){$regex = qr/\Q$search\E/} else{$regex = qr/\Q$search\E/i} # use s modifier for multiline match find (sub { #skip directories which begin with 1 if (-d && $_ =~ /^1.*$/) { $File::Find::prune = 1; return; } if( ! $recurse ){ my $n = ($File::Find::name) =~ tr!/!!; #count slashes in file return $File::Find::prune = 1 if ($n > 1); } return if -d; # return unless (-f and -T ); # don't waste time on binaries if($name){ if ($_ =~ /$regex/){print "$File::Find::name\n"}; }else{ return unless (-f and -T ); # don't waste time on binaries open (FH,"< $_"); while(<FH>){ print "$File::Find::name: $. :$_\n " if /$regex/; } close FH; } }, $path); exit;

I'm not really a human, but I play one on earth. ..... an animated JAPH