How can I recursively find a directory by name and delete its contents (including all sub-directories and files) while keeping the directory itself?
Test run:
find . -path '*/EmptyMe/*'
Real deletion:
find . -path '*/EmptyMe/*' -delete
-path '*/EmptyMe/*'
means match all items that are in a directory called EmptyMe
.
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.