Xref: feenix.metronet.com comp.unix.questions:8632
Newsgroups: comp.unix.questions
Path: feenix.metronet.com!news.ecn.bgu.edu!usenet.ins.cwru.edu!howland.reston.ans.net!noc.near.net!uunet!boulder!wraeththu.cs.colorado.edu!tchrist
From: Tom Christiansen <tchrist@cs.Colorado.EDU>
Subject: Re: Finding files in search-paths -- how??
Message-ID: <1993Jul28.165946.3399@colorado.edu>
Originator: tchrist@wraeththu.cs.colorado.edu
Sender: news@colorado.edu (The Daily Planet)
Nntp-Posting-Host: wraeththu.cs.colorado.edu
Reply-To: tchrist@cs.colorado.edu (Tom Christiansen)
Organization: University of Colorado, Boulder
References: <aec1.743779622@crux1.cit.cornell.edu>
Date: Wed, 28 Jul 1993 16:59:46 GMT
Lines: 47

From the keyboard of aec1@crux4.cit.cornell.edu (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