Wildcard for arbitrary depth
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/*.
Related videos on Youtube
sawa
Updated on September 18, 2022Comments
-
sawa over 1 year
I want to use
grep
where paths are arbitrary depth under the directory/path/to/dir
and has the file namefoo
. I thought that the wildcard for arbitrary depth is**
, and I triedgrep 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 namefoo
?-
Admin over 9 yearsIs this a difficult thing? I expected that only I didn't know.
-
Admin over 9 yearsAn alternative is
cat `find . -name foo` | grep some_pattern
-
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 almost 8 yearszsh is not available everywhere.