Delete all folders containing files which match pattern

directoryfindrm

I'm trying to delete all subdirectories of my current working directory which contain a rar file.

My first attempt: find -name *.rar -exec rm -r {}/.. ';' failed because that is not a valid directory. I tried using dirname {} for a more sensible command, but decided to just ask after almost deleting stuff I didn't mean to.

I'm using Cygwin on Windows 7.

Best Answer

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.

Related Question