Unix & Linux
bash find
Updated Thu, 01 Sep 2022 15:35:38 GMT

find the directory using pattern and delete the content, not the directory itself


I could traverse the directory sizes using pattern in find command:

find . -name "results_*" -exec du -sm '{}' \;

Now I would like to delete the content of those directories, but still retaining those directories themselves (the results_*) to create a placeholder that they existed and could be found in a backup.

How could I do that?




Solution

You can match against the path instead:

find . -path "*/results_*/*" -delete

or, if your find doesnt support -delete,

find . -path "*/results_*/*" -exec rm -rf {} \; -prune

This finds anything with results_* in its path, excluding the last path component; so all the contents of directories match results_* will be deleted, but the directories themselves will be left alone (unless they are themselves inside a directory matching results_*).