How to delete all subdirectories with a specific name

bash, gnu-findutils, linux, shell

Solution

If `find` finds the correct directories at all, these should work:

find dir -type d -name "subdir1" -exec echo rm -rf {} \; 

or

find dir -type d -name "subdir1" -exec echo rm -rf {} +

(the `echo` is there for verifying the command hits the files you wanted, remove it to actually run the `rm` and remove the directories.)

Both piping to `xargs` and to `while read` have the downside that unusual file names will cause issues. Also, `find -delete` will only try to remove the directories themselves, not their contents. It will fail on any non-empty directories (but you should at least get errors).

With `xargs`, spaces separate words by default, so even file names with spaces will not work. `read` can deal with spaces, but in your command it's the unquoted expansion of `$tar` that splits the variable on spaces.

If your filenames don't have newlines or trailing spaces, this should work, too:

find ... | while read -r x ; do rm -rf "$x" ; done

Problem

I'm working on Linux and there is a folder, which contains lots of sub directories. I need to delete all of sub directories which have a same name. For example, ``` dir |---subdir1 |---subdir2 | |-----subdir1 |---file ``` I want to delete all of `subdir1`. Here is my script: ``` find dir -type d -name "subdir1" | while read directory ; do rm -rf $directory done ``` However, I execute it but it seems that nothing happens. I've tried also `find dir -type d "subdir1" -delete`, but still, nothing happens.

Original source