[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: grep recursive

From: Pitcher, Michael
Subject: RE: grep recursive
Date: Mon, 18 Jul 2011 12:34:39 +0000

Points taken.
The gist of this msg was recursive use of grep and as you pointed out, 'find' 
works better.
Thanks, Bob!
-- mike

-----Original Message-----
From: Bob Proulx [mailto:address@hidden 
Sent: Sunday, July 17, 2011 2:18 AM
To: Pitcher, Michael
Cc: address@hidden
Subject: Re: grep recursive

Pitcher, Michael wrote:
> server112-test/$ls -a -R .
> ...
> As you can see, ls -a shows all files.
> Suppose I want to search recursively for a string ("test") in a
> file. Normally I would expect the same rules to apply as for "ls" -
> ignore hidden files. But grep doesn't work that way:
> server112-test/$grep -R test *

They would if you used grep the same way as you used ls.  For ls you
gave it a ".".  But for grep you gave it a "*".  That is the source of
your differences.  If you gave ls "*" then it would have had the same

> Hmm. (Also, why did it skip ./.foo? Hmm.)

Because grep was not told to search it.  "*" does not match a '.' in
filenames.  Therefore when the shell expanded the "*" fileglob it did
not expand to match that file.

You can verify what the shell is doing by using echo.  Try this:

  $ echo grep -R test *

And you will see that the "*" did not expand to match the .foo entry.

What you wanted to say was:

  $ grep -R test .

> Now, suppose I want to recursively search all files, skipping the
> files in the hidden directories, ".foo".  Ok, this works for
> "./.foo" but - oops - not bar/.foo:

Recursive traversal is one of those features that should never have
been added to grep.  Because it already existed in 'find' and to a
very high level of functionality.  But once grep added recursive
searching then people started asking for including and excluding and
all kinds of other extra feature creep.  My advice is to leave all of
that behind.  If you are doing anything more than grep -r PAT . then
instead you are much better off using find.

  find . -type f -exec grep PATTERN {} +

Want to skip .foo everywhere?

  find . -name .foo -prune -o -type f -exec grep PATTERN {} +

By learning how to use 'find' you will be learning a very useful tool
in the toolbox.

> Linux version 2.6.9-22.ELsmp (address@hidden) (gcc version 3.4.4 20050721 
> (Red Hat 3.4.4-2)) #1 SMP Mon Sep 19 18:00:54 EDT 2005
> Linux server112  2.6.9-22.ELsmp #1 SMP Mon Sep 19 18:00:54 EDT 2005 x86_64 
> x86_64 x86_64 GNU/Linux

The version of the kernel and that it is 64-bit isn't relevant for the
questions you are asking about grep.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]