Using grep recursively

grep has the ability to search recursively using the option -r. However, I was wondering if grep would be able to search the query string recursively for a certain number of levels of subfolders. For example, I have a folder rootthat has folders parent1, parent2, ..., parentN. Each parent folder has regular text files and folders called child1, child2, ..., childM. I would like to run grep from the root level and search the files inside the parents without looking at the child folders. Is there an easy way to do this?

+5
source share
2 answers

you can try:

Grep

 --exclude=GLOB
              Skip files whose base name matches GLOB  (using
              wildcard  matching).   A file-name  glob  can  use *,
              ?, and [...]  as wildcards, and \ to quote a wildcard
              or backslash character literally.

       --exclude-from=FILE
              Skip files whose base name matches any of the file-name
              globs  read  from FILE (using wildcard matching as
              described under --exclude).

       --exclude-dir=DIR
              Exclude directories matching the pattern DIR from
              recursive searches.

or use this find | xargs grep

with find you can determine the level

EDIT

linux/unix. , .

echo "abc"|sed 's/a/x/'
find . -name "*.pyc" |xargs rm
awk 'blahblah' file | sort |head -n2 
tree|grep 'foo'
mvn compile|ack 'error'
...

, . .

+6

Kent , grep; . , find , , , find grep.

man find, man- , find. -maxdepth.

. , , :

  • find . , (.) -.

  • find . -maxdepth 1 . find . -maxdepth 2 . ...

  • , . , grep , . -type f, : find . -maxdepth 2 -type f.

, , grep . - xargs:

find . -maxdepth 2 -type f | xargs grep <text-to-search-for>

| " ", "stdout", find (.. , ) xarg " ", "stdin", .. , .

xargs - , , (, grep <text-to-search-for>), , stdin. grep , find.

, , xargs , , . ( ), find.

-exec find, , , ; +. {} ( { }), . find , , .

, , :

find . -type f -maxdepth 2 -exec grep <text-to-search-for> {} +

( + ; . man find, , + , , {} .)

+10

All Articles