0

I want to find a directory x inside a particular subdirectory y using the macOS terminal, but I do not know the directories preceding y.

This command - find / -type d -name "x" works for finding x, but there are many directories named x across the system so I need to find the x which is under the directory y.

I tried -

  • find / -type d -name "/y/x" or
  • find / -type d -name "y/x" or
  • find / -type d -name "../y/x"

but these do not show me the desired result.

3

Using the -path primary:

find / -path '*y/x'
-path pattern
         True if the pathname being examined matches pattern.  Special shell pattern matching characters (``['', ``]'', ``*'', and ``?'') may be used as part of
         pattern.  These characters may be matched explicitly by escaping them with a backslash (``\'').  Slashes (``/'') are treated as normal characters and do
         not have to be matched explicitly.
1

From a zsh shell:

print -rC1 -- /**/y/x(/D)

The ** glob matches down into subdirectories, and the (/D) glob qualifier specifies that the resulting pathnames must be directories and that the pattern should match hidden names too (as with dotglob in bash).

Or the approximate equivalent from bash release 4 or later (i.e., installed from Homebrew on macOS, not the default bash):

shopt -s globstar failglob dotglob
printf '%s\n' /**/y/x/

The globstar shell option in bash enables the use of the ** globbing pattern, while failglob makes pattern matching fail with an error if there aro no matches. The failglob behaviour is the default in zsh, as is the availability of **.

find would probably be faster though:

find / -type d -path '*/y/x'

This would find any directory called x living in a directory called y somewhere under /.

Or, you may have a functional locate utility with which you may do

locate '*/y/x'

This would be the fastest alternative, but would only return results accessible by any user on the system, and may not be entirely up to date.

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.