in reply to Search thru directories of .c & .h files for @Constants
use strict; use File::Find; # Perl script to search files for particular strings. # Recurses into subdirectories. # If you don't specify a directory to search on the command line, # it will default to the current directory. # define strings to look for here: my @Constants = ( "foo", "bar", "baz", ); my $path = $ARGV[0] || "."; my $count=0; find( sub { my $n = $File::Find::name; # search for files ending in .h or .c if ($n =~ /\.h$/ || $n =~ /\.c$/ ) { ++$count; # might want to use die instead of warn open(IN, "$n") or warn "can't open file $n : $! "; while (<IN>) { my $line = $_; for my $search_string (@Constants) { # the "i" makes the match case insensitive if ($line =~ /$search_string/i) { # print filename and line number and matching string print "$n : $. : $search_string\n"; } } } close (IN); } }, $path); print "Found matches in $count files.\n";
update: Fixed typo in original post - the path should default to the current working directory. Also, looking at Grandfather's reply, if you want a pattern like "foo" to NOT match something like "food" or "foobar", change the pattern match line to this:
if ($line =~ /\b$search_string\b/i) {
This adds "end of word boundary" around the pattern.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Search thru directories of .c & .h files for @Constants
by pmonk4ever (Friar) on Sep 19, 2007 at 19:10 UTC |