Wildcard for arbitrary depth

5,450

Solution 1

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

Solution 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/*.
Share:
5,450

Related videos on Youtube

sawa
Author by

sawa

Updated on September 18, 2022

Comments

  • sawa
    sawa over 1 year

    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?

    • Admin
      Admin over 9 years
      Is this a difficult thing? I expected that only I didn't know.
    • Admin
      Admin over 9 years
      An alternative is cat `find . -name foo` | grep some_pattern
    • Admin
      Admin over 9 years
      @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!
  • Nick Volynkin
    Nick Volynkin almost 8 years
    zsh is not available everywhere.