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 for help after almost deleting stuff I didn't mean to.

Excellent tip. This still doesn't quite work when the directory names contain spaces. I solved this by swapping the second line to sed 's/^/"/g' toremove | sed 's/$/"/g' | xargs rm -r
–
MikeFHayDec 31 '12 at 1:27

1

This will not work on files with spaces. Also will break if the current directory contains a *.rar file due to lack of quoting.
–
jordanmDec 31 '12 at 3:28

@MikeL: Thanks for the improvement; I replaced the second command with your version.
–
cpastDec 31 '12 at 3:39

2

@MikeL This is good enough for you because Windows filenames can't contain \" or newlines, but in general, this method is unsafe. There's no convenient way to use xargs (except xargs -0) with arbitrary file names. It's usually better to use find -exec.
–
GillesJan 1 '13 at 1:14

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:

for dir in */; do # iterate all subdirectories
touch $dir"dummy.rar" # create a "rar"-file...
for file in $dir*.rar; do # ...so this won't break on zero such
rm $file # remove the dummy, and all archives
done
done