Delete all folders containing files which match pattern
With zsh:
rm -rf **/*.rar(:h)
The suffix :h
applies the history expansion modifier h
(“head”) which removes the basename of each match, keeping only the directory part.
Make sure to check that these are really the directories you want to delete! For example, move them to a temporary directory first:
mkdir DELETE
mv **/*.rar(:h) DELETE/
# check that you really want to delete everything in DELETE
rm -r DELETE
You can use bash -c
to perform more advanced operations in and -exec
for find. The problem with using a temp file and cat in combination with xargs
is that it will break if a file contains a space, newline, or tab. The following should work:
find . -type f -name '*.rar' -exec bash -c 'rm -rf "${@%/*}"' -- {} +
Using +
for find with "$@" will execute rm
one time like with xargs
.
You could do it with a pair of statements.
First, get a list of directories to remove using
find -name *.rar -exec dirname {} ';' > toremove
Next, cat toremove
to make sure it has the folders you want. Then, pass it to rm -rf
using
sed 's/^/"/g' toremove | sed 's/$/"/g' | xargs rm -r
Last, rm toremove
.