3

I want to use grep where paths are arbitrary depth under the directory /path/to/dir and has the file name foo. I thought that the wildcard for arbitrary depth is **, and I tried

grep some_pattern /path/to/dir/**/foo

but it seems to be matching only files where the ** part represents a single directory depth like

/path/to/dir/bar/foo

How can I match paths for arbitrary depth that is under the directory /path/to/dir and has the file name foo?

3
  • Is this a difficult thing? I expected that only I didn't know.
    – sawa
    Sep 23 '14 at 15:53
  • An alternative is cat `find . -name foo` | grep some_pattern
    – Harvinder
    Sep 23 '14 at 17:24
  • @Harvinder better use find . -name foo | xargs grep some_pattern since the number of files might otherwise exceed the maximum size of command line arguments. Even better: find . -name foo -print0 | xargs -0 grep some_pattern!
    – Celada
    Sep 23 '14 at 18:39
3

Use zsh. In the zshexpn(1) man page, Section "Recursive Globbing":

A pathname component of the form '(foo/)#' matches a path consisting of zero or more directories matching the pattern foo.

As a shorthand, '**/' is equivalent to '(*/)#'; note that this therefore matches files in the current directory as well as subdirectories.

[...] This form does not follow symbolic links; the alternative form '***/' does, but is otherwise identical.

This also means that ** doesn't include hidden directories (whose name starts with a dot) by default. If you want to match them, either set the GLOB_DOTS option or use the D glob qualifier:

grep some_pattern /path/to/dir/**/foo(D)

With bash, you need to explicitly set the globstar option to make ** work:

shopt -s globstar
1
  • 1
    zsh is not available everywhere. Jun 10 '16 at 5:19
2

In addition to vinc17's suggestion, you can use --include combined with -r option, something like:

grep -r --include \foo some_pattern /path/to/dir/*.

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.