Subject: Re: Finding files in search-paths -- how??
From: Tom Christiansen <[email-masked]>
Date: Wed, 28 Jul 1993 16:59:46 GMT
Newsgroups: comp.unix.questions

From the keyboard of [email-masked] (Allen Chen):
:I think this should be a simple thing to do, but no one around here seems
:to know!  So, how would I search for files in my search-path (without
:actually going into each path maunally, etc...)?  Is there a command for
:this or would I have to use find?   As far as I have been able to tell, the
:search-path only gets searched when trying to execute a file...  
:Thanks in advance!

Here's the "wh" command I use:

    #!/usr/bin/perl
    foreach $file (@ARGV) {
	foreach $dir (split(/:/,$ENV{PATH})) {
	    -x ($path="$dir/$file") && print "$path\n";
	} 
    }

Another intersting one is pgrep, or pathgrep:

    #!/usr/bin/perl
    chop($cwd = `pwd`) unless $cwd = $ENV{PWD};
    $regexp = shift || die "usage: $0 regexp\n";
    for $dir (split(/:/,$ENV{PATH})) {
	chdir($dir =~ m#^/# ? $dir : "$cwd/$dir") || next;
	opendir(DOT, '.') || next;
	while ($_ = readdir(DOT)) {
	    next unless -f;
	    next unless -x _;
	    next unless /$regexp/o;
	    print "$dir/$_\n";
	} 
    }

Here's another, much faster version of pgrep, but arguably less correct.

    #!/usr/bin/perl
    $regexp = shift || die "usage: $0 regexp\n";
    for $dir (split(/:/,$ENV{PATH})) {
	opendir(DOT, $dir) || next;
	while ($_ = readdir(DOT)) {
	    next unless /$regexp/o;
	    print "$dir/$_\n";
	} 
    }

--tom