7

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.

3
  • Nest it maybe ? find . -name 'EmptyMe' -type d -exec find {} -type f -delete \; Let me know if you want this as actual answer Commented Aug 16, 2018 at 20:55
  • That didn't remove sub-directories of EmptyMe.
    – temuri
    Commented Aug 16, 2018 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
    Commented Aug 16, 2018 at 21:29

3 Answers 3

10

Test run:

find . -path '*/EmptyMe/*'

Real deletion:

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

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

0
3

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.

0

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
4
  • Can you please update the accepted answer with the fix to avoid this error?
    – temuri
    Commented Aug 23, 2018 at 13:49
  • @temuri They're different solutions, so i put them in different answers
    – wjandrea
    Commented Aug 23, 2018 at 14:41
  • Sorry, it's not clear which solution exactly would avoid "No such file or directory" error. Can you please clarify?
    – temuri
    Commented Aug 23, 2018 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
    Commented Aug 23, 2018 at 17:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .