Search code examples
linuxbashfindexec

Use Linux Find to search for directories that contain a file with properties


I'm trying to find projects in an enormous directory. The projects are always several levels of depth in and have a config file which contains the project name. So basically...

Given a path and string Return any directory that has a depth of 3 from the and contains a file named "config" that contains the

I learned that find combined with grep will work... but print out the grepped text and not the path of it's parent directory

find <starting-dir> -maxdepth 3 -mindepth 3 -type d -exec grep '<project-name>' {}/config \;

Just prints out the project name :(

Perhaps there any way to switch back to find's default behaviour of printing out the found file path only if the grep is successful? Or is there another tool I should try to use to solve this?


Solution

  • To get -print, you need to add it explicitly after a succesful -exec.

    For example, using grep's -q:

    find <starting-dir> \
        -maxdepth 3 -mindepth 3 \
        -type d \
        -exec grep -q '<project-name>' {}/config \; \
        -print
    

    As you discovered, grep already has -l.

    You can reduce the number of grep processes:

    find <starting-dir> \
        -maxdepth 4 -mindepth 4 \
        -type f -name config \
        -exec grep -l '<project-name>' {} +