wildcards – How to Recursively Delete Directories with Wildcard

recursivermwildcards

I am working through SSH on a WD My Book World Edition. Basically I would like to start at a particular directory level, and recursively remove all sub-directories matching .Apple*. How would I go about that?

I tried

rm -rf .Apple* and rm -fR .Apple*

neither deleted directories matching that name within sub-directories.

Best Answer

find is very useful for selectively performing actions on a whole tree.

find . -type f -name ".Apple*" -delete

Here, the -type f makes sure it's a file, not a directory, and may not be exactly what you want since it will also skip symlinks, sockets and other things. You can use ! -type d, which literally means not directories, but then you might also delete character and block devices. I'd suggest looking at the -type predicate on the man page for find.

To do it strictly with a wildcard, you need advanced shell support. Bash v4 has the globstar option, which lets you recursively match subdirectories using **. zsh and ksh also support this pattern. Using that, you can do rm -rf **/.Apple*. This is not POSIX-standard, and not very portable, so I would avoid using it in a script, but for a one-time interactive shell action, it's fine.