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


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


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.

  • Nest it maybe ? find . -name 'EmptyMe' -type d -exec find {} -type f -delete \; Let me know if you want this as actual answer – Sergiy Kolodyazhnyy Aug 16 '18 at 20:55
  • That didn't remove sub-directories of EmptyMe. – temuri Aug 16 '18 at 21:14
  • 1
    @Sergiy You need -mindepth 1 for the nested command, and remove -type f cause OP wants to remove directories too. – wjandrea Aug 16 '18 at 21:29

Test run:

find . -path '*/EmptyMe/*'

Real deletion:

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

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

| improve this answer | |

One option that can be used is to nest the commands:

find . -type d -name 'EmptyMe'  -exec find {} -mindepth 1 -delete \;

The outer find -type d -name 'EmptyMe' locates the required directories, and runs the inner find command via -exec ... \;. The inner command descends into the found directory (referenced via {} ) and since we're using -delete flag here, it should follow depth-first search, removing files and then subdirectories.

| improve this answer | |

This works, but it gives errors if EmptyMe directories are empty.

find . -name 'EmptyMe' -type d -exec sh -c 'rm -r -- "$1"/*' sh {} \;

Error example:

rm: cannot remove ‘./EmptyMe/*’: No such file or directory
| improve this answer | |
  • Can you please update the accepted answer with the fix to avoid this error? – temuri Aug 23 '18 at 13:49
  • @temuri They're different solutions, so i put them in different answers – wjandrea Aug 23 '18 at 14:41
  • Sorry, it's not clear which solution exactly would avoid "No such file or directory" error. Can you please clarify? – temuri Aug 23 '18 at 17:05
  • @temuri Oh, gotcha. Sergiy's answer and my other one both avoid this error because they don't assume the EmptyMe directories have contents. – wjandrea Aug 23 '18 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.