Recursively find all files that match a certain pattern

bash, command-line, macos

Solution

With gnu find you can use regex, which (unlike `-name`) match the entire path:

find . -regex '.*/foo/[^/]*.doc'

To just count the number of files:

find . -regex '.*/foo/[^/]*.doc' -printf '%i\n' | wc -l

(The `%i` format code causes `find` to print the inode number instead of the filename; unlike the filename, the inode number is guaranteed to not have characters like a newline, so counting is more reliable. Thanks to @tripleee for the suggestion.)

I don't know if that will work on OSX, though.

Problem

I need to find (or more specifically, count) all files that match this pattern: */foo/*.doc Where the first wildcard asterisk includes a variable number of subdirectories.

Original source