2

I would like to delete wildcard throughout all subdirectories under the directory where I run the command.

1
  • This is not clear. It looks like you are using the word "wildcard" to describe something else. Edit the question to make it clearer. Avoid technical words. Jul 18 '20 at 14:04
1
find . -name '*.unwanted' ! -type d -delete

Would delete the files whose name matches the *.unwanted wildcard (except those of type directory¹) in the current directory and sub-directories below. If you remove the ! -type d, it would also remove directory files, but only if they're not empty.

Note that it also removes hidden files and files in hidden directories.

-delete is a BSD extension (so would work in macOS) also found in a few other find implementations including GNU find but is not standard (replace with -exec rm -f {} + if your find doesn't support it).

As the default interactive shell in macOS is now zsh, at the shell prompt, you should also be able to do the same with:

rm -f -- **/*.unwanted(D^/)   # same as find above, D for dot (hidden) files
rm -f -- **/*.unwanted(^/)    # skip hidden files and dirs
rm -f -- **/*.unwanted(-^/)   # consider the type of file after symlink resolution
rm -f -- ***/*.unwanted(^/)   # follow symlinks when traversing the
                              # directory tree (same as find -L)

You may however run into a argument list too long error if there's a large number of files, which could be worked around with zargs or by making the rm command builtin with zmodload zsh/files.

Both find predicates and zsh glob qualifiers (the part in (...)) can further refine which files you want to delete. Some examples:

  • -type f / (.): regular files only (in place of ! -type d / (^/))
  • -mtime -7 / (m-7): not older than 7 days
  • -size +1000000c / (L+1000000): bigger than 1MB.
  • -exec cmd {} \; / (e['cmd $REPLY']), files for which cmd returns true.
  • etc. See the man/info documentation of find/zsh for details (info zsh qualifiers).

¹ It would however remove symbolic links, whether they point to files of type directory or not

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.