#!/usr/bin/perl # -d for debugging purposes ############################################################################### # Search for up to 2 strings within files in current directory and all sub-dir # file names are searched # (optionally, you can supply a -c flag to search file contents as well) # If found, print the name of the file. # # Author: Sam Sultan # # syntax: search [-c] string1 [string2]; -c search file contents also ############################################################################### local(@arg) = @ARGV; # arg = passed args @ARGV $type = $arg[0]; # type = first arg if ($type eq '-c') { # search file contents also shift(@arg); # pop arg1 off the @arg array } &search($type,@arg); # call search subroutine ############################################################################# sub search { my($type,$arg1,$arg2) = @_; # arg = passed args @_ $arg1 =~ tr/A-Z/a-z/; # translate arg1 to lower case $arg2 =~ tr/A-Z/a-z/; # translate arg2 to lower case open(FIND, "find . -print |") # open pipe from Unix cmd || die "Could not open find command. Error $!\n"; LOOP: while ($filename = ) { # $filename = next row chop $filename; # remove newline char $found1 = $found2 = 0; # set found1 & found2 = NO if ($arg2 eq '') {$found2 = 1;} # if no arg2, set found2 = YES ####### Search file names ######## ($fname = $filename) =~ tr/A-Z/a-z/; # trans fname to low case if (($fname =~ /$arg1/) && # if fname contain arg1 ($fname =~ /$arg2/)) { # and arg2 print "$filename\n"; # print next LOOP; # loop to next file } ####### Search file contents ######## next LOOP unless -T $filename; # skip if file is non-text if ($type eq '-c') { # if search contents also if (!open(TEXTFILE, $filename)) { # open file TEXTFILE print STDERR "Cannot open $filename - continuing...\n"; next LOOP; } while () { # read data line $line = $_; # copy the line $_ =~ tr/A-Z/a-z/; # trans data to lower case if ($found1 || $_ =~ /$arg1/) # if data contain arg1 {$found1 = 1;} # arg1 is found if ($found2 || $_ =~ /$arg2/) # if data contain {$found2 = 1;} # arg2 is found if ($found1 * $found2) { # if both args are found print "$filename\n"; # print filename print "$line"; # print original line close(TEXTFILE); # close file next LOOP; # loop to next file } } } } }