Ubuntu – How to recursively find a directory by name and delete its contents (including all sub-directories and files) while keeping the directory itself

command linefindrm

Given:

  1. I have a tree structure with folders EmptyMe on different levels
  2. EmptyMe directories contain sub-directories and files

Required:

  1. Empty contents of EmptyMe directories (including their sub-directories), while keeping those directories (not deleting them).

Question:

What's the Unix command to recursively find all EmptyMe directories from current level and delete all of their contents (including sub-directories), while keeping EmptyMe directories on the disc?

My attempt:

$ find . -name 'EmptyMe' -type d -exec rm -- {} +
rm: cannot remove `./a/b/c/d/EmptyMe': Is a directory

As you can see, that command attempted to remove EmptyMe, as opposed to its contents.

Best Answer

Test run:

find . -path '*/EmptyMe/*'

Real deletion:

find . -path '*/EmptyMe/*' -delete

-path '*/EmptyMe/*' means match all items that are in a directory called EmptyMe.