I want to grep for interesting string, but only in specific folder/file combinations, such as myfolder/myfile.out.

The directory I'm grepping from may have these combinations in subdirectories of varying depths (otherwise I could just grep 'interesting string' myfolder/myfile.out) and I also do not want to get results from any myfile.out that is located in a directory with a different name, for example /deeply/nested/directory/structure/myfolder/myfile.out shall be grepped, but not /deeply/nested/directory/structure/notmyfolder/myfile.out.


If I understand this correctly you are looking for something like:

find . -path "*/myfolder/myfile.out" -exec grep <string> /dev/null {} +
  • This works, but I get an xargs warning a NUL character occured in the input. It cannot be passed through in the argument list. Did you mean to use the --null option? – snurden Mar 2 '16 at 10:20
  • just edit the answer to a more suitable answer. the previous one had an error that would take into account myfile.xyz files as well. – BitsOfNix Mar 2 '16 at 10:31

In zsh, the **/ glob means “under any level of directory nesting”:

grep 'interesting string' **/myfolder/myfile.out

In bash: shopt -s globstar then as above. Beware that in bash ≤4.2 this traverses symbolic links to directories. This feature doesn't exist yet in the ancient version of bash on OSX.

In ksh93: set -G then as above.

This may fail if the total length of the file names is too long. In this case, you can fall back to calling find which will run grep in batches:

find -path '*/myfolder/myfile.out' -exec grep -H 'interesting string' {} +

or if you can't rely on GNU tools:

find -name myfolder -exec sh -c 'grep "$0" /dev/null "$1/myfile.out"' 'interesting string' {} \;

though if you have zsh then it once again comes to the rescue with zargs:

zargs -- **/myfolder/myfile.out -- grep 'interesting string' /dev/null

A different approach is to use a different tool that combines grep and directory traversal in fancier ways than GNU grep. For example you can use the silver searcher:

ag -G '/myfolder/myfile\.out$' 'interesting string'

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.