3

I want to search within file contents, recursively on subdirectories, but I only care about whether the first level subdirectory contains any matches. That is, given:

ParentDirectory
    Subdirectory1
        File containing match
        File not containing match
        File containing match
    Subdirectory2
        File not containing match
        File not containing match
    Subdirectory3
        File not containing match
        Subdirectory3.1
            File containing match

I need to know:

Matches:
ParentDirectory/Subdirectory1
ParentDirectory/Subdirectory3

Can someone provide a way to do this with grep or similar utility?

4
  • So you have to search all of the subdirectories, but you only want to report matches based on the first-level subdirectory?
    – Jeff Schaller
    Sep 4 '19 at 13:36
  • What I'm trying to clarify is that you don't need files that are directly in "subdirectory3" to match in order to report it.
    – Jeff Schaller
    Sep 4 '19 at 13:42
  • @jeff-Schaller yes (which also means search can stop at first match in a given level of subdirectory)
    – taz
    Sep 4 '19 at 13:44
  • I'd do it with find and a maxdepth to limit what files are looked in, then use the -exec option for your grep or pipe through xargs. find . -maxdepth 2 -type f -exec grep -H searchterm {} \;
    – ivanivan
    Sep 4 '19 at 14:07
2

Use find to run recursive grep on each subdirectory:

echo "Matches:"
find ParentDirectory -mindepth 1 -maxdepth 1 -type d \
  -exec grep -rq pattern {} \; \
  -and -print

-q option lets grep stop at first match
-and -print will make find print the directory only when grep found something.


Alternative with a for-loop:

echo "Matches:"
for d in ParentDirectory/* ; do
    [ -d "$d" ] && grep -rq pattern "$d" && echo "$d"
done

Output for either version:

Matches:
ParentDirectory/Subdirectory1
ParentDirectory/Subdirectory3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.