I am always looking at other people's code to find examples of what I want to do. Where I work we have directories full of code, and I found it a hassle to wade through each directory to grep through the files.
This should also be possible with a combination of xargs and grep, but I liked this solution better, with line numbers and path location included. Also allows users to specify a filename pattern, example searching pl or php or html files.
Comments would be very appreciated.
#!/usr/bin/perl -w
# By Greg Flanders gflan@NO.avalon.SPAM.net.THANKS
#
# Opens each file from currenct directory and searches
# for the pattern given. Jumps down directories to search
# recursively.
use strict;
use File::Find;
use Cwd;
my $directory = getcwd();
my$searchstring = $ARGV[0];
my $ext = $ARGV[1];
print "$searchstring\n";
die "Usage : ggrep searchstring extension\n" if ($searchstring eq "");
find (\&process_file, "$directory");
sub process_file {
return if -d;
if ($_ =~ /$ext/i) {
open (INPUT, "< $_");
foreach (<INPUT>) {
if(/$searchstring/i) {
$_ = substr($_, 0, 60);
s/^\s*//;
print "$File::Find::name\:$.\:\t$_\n";
}
}
close INPUT;
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.