grep

Marcus Hall marcus at illusion.uucp
Wed Apr 17 04:58:20 AEST 1991


In article <4037 at risky.Convergent.COM> sundrag at risky.Convergent.COM (Sundaraswaran Gopalakrishnan) writes:
>In article <1991Apr14.214414.9815 at hellgate.utah.edu>, mmoore%hellgate.utah.edu at cs.utah.edu (Michael Moore) writes:
>> 	Does anyone know if there is an easy way to recursively search for a 
>> pattern down the entire file tree of a directory?  
>
>You can do the following :
>find / -print | xargs grep <pattern>
>or,
>find / -name "*.c" -print | xargs grep <pattern>
>
>xargs constructs the argument list from its input and 'll
>apply grep to each argument ( which is different from just 
>"find / -print | grep <pattern>", which 'll look for a *file*
>that matches <pattern> )
>
>Sundar, Unisys

Unfortunately, grep causes a slight problem with this.  The problem is that
if grep has two or more file arguments it prints the file name and a colon
before the matched lines.  If it has a single file argument, it does not.

Now, xargs collects some number of lines from stdin and gives them to grep
as file arguments (or so grep interprets them).  After potentially kicking
off several greps, if there is only one line left on xarg's stdin, it will
kick off a new grep with a single argument.  If this grep matches any lines,
it will not output the file name, just the matched lines.  Thus, it will
be unclear just where these lines came from!

There is no option to force grep to output the file name, but one trick that
can be used to do this is to always give grep an extra argument.  If this
is "/dev/null", then grep cannot possibly match anything in it, so it is
effectively a noop, but it does force grep to output file names.  Thus, the
commands from above should be written as:

find <dir>... -type f -print | xargs grep <pattern> /dev/null
- or -
find <dir>... -type f -name "*.c" -print | xargs grep <pattern> /dev/null

(The "-type f" is there because you probably don't want to do grep through
directories and especially you do not want to do it through /dev files!!)

marcus hall



More information about the Comp.unix.questions mailing list