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.

Kevin Bowen
  • 19,615
  • 55
  • 79
  • 83
temuri
  • 185

3 Answers3

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.

wjandrea
  • 14,236
  • 4
  • 48
  • 98
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.

wjandrea
  • 14,236
  • 4
  • 48
  • 98
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
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
wjandrea
  • 14,236
  • 4
  • 48
  • 98
  • 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