NYCPHP Meetup

NYPHP.org

[nycphp-talk] Search function

Steve Manes smanes at magpie.com
Fri Sep 19 21:58:40 EDT 2008


(Margaret) Michele Waldman wrote:
> Does anyone know of a function or code I could use to quickly search my 
> site for a document?

If you want something permanent for your web site, this is the GNU 
successor to ht://Dig.

http://hyperestraier.sourceforge.net/

Otherwise, for shell searches I use this handy little perl script I've 
had for about 12 years.  It could be converted to a CGI script pretty 
easily (with appropriate security considerations).

#!/usr/bin/perl
# tgrep
# grep only text files (ignore binary files)
#
# Usage: tgrep [-l] pattern [files]

$nameonly = 0;

if ($ARGV[0] eq '-l') {
     $nameonly = 1;
     shift;
}

# Get pattern and protect the delimiter.
$pat = shift;
$pat =~ s/!/\\!/g;

&dodir("");

sub     dodir
{
     local($dir) = @_;
     local(@names);

     opendir(DIR, ".") || die "Can't open directory .\n";
     @names = readdir(DIR);
     closedir(DIR);

     foreach $file (@names) {
         next if $file eq '.';
         next if $file eq '..';

         if (-d $file) {
             chdir $file || die "Can't chdir to $file";
             &dodir("$dir/$file");
             chdir("..");
             next;
         }

         next if -B $file;       # Ignore binaries

         open(FILE, "<$file") || do {
             print "Can't open $file: $!\n";
             next;
         };

         while (<FILE>) {
             if ( m!$pat! ) {
                 if ($nameonly) {
                         print "$dir/$file\n";
                 }
                 else {
                         print "$dir/$file",":\t",$_;
                 }
             }
         }
         close FILE;
     }
}



More information about the talk mailing list