I would like to delete all sub-directories and files in a given directory except directories that match a certain pattern:


General setup: I generated several models (> 100) with each having >=1 generation(s). Within those models (e.g., example_dir/model-0/gen-0/) are several directories and sub-directories.

Desired result: I would like to delete all directories and files except the ones that match:


Within each single model/gen/ it would be something like this?:

rm -rf !(share)

I’m not sure I entirely understand your question, and I’m not sure what follow-up questions make sense.  One thing I’m wondering is, if you have a directory tree like

|-- model-0
|   |-- gen-0
|   |   |-- share
|   |   |-- trash
|   |   |   |-- more_trash
|   |   |-- file123.txt
|   |-- grandfather
|-- platypus

is it sufficient to delete example_dir/model-0/gen-0/trash (and its contents), or do you also want to delete example_dir/model-0/grandfather, example_dir/platypus and foo?  And how about example_dir/model-0/gen-0/file123.txt?

If you want to delete trash (and its contents) and file123.txt, try

shopt -s extglob
echo rm -rf example_dir/model-*/gen-*/!(share)

If you want to delete trash (and its contents) but preserve file123.txt, try

shopt -s extglob
echo rm -rf example_dir/model-*/gen-*/!(share)/

(adding a / after !(share)).

Either way, look over the output carefully, and, if you’re sure it’s what you want, run the command again without the echo.

If you also want to delete top-level directories other than example_dir, first-level directories that don’t match the model-* pattern, or second-level directories that don’t match the gen-* pattern, please edit your question to clarify.

  • I think rm -rf example_dir/model-*/gen-*/!(share) is what I need. Thank you! I will run a test on a fake-directory first. The directory tree only has sub directories beside share. Otherwise it is always example_dir/model-*/gen-*/ – Stefan Crummenerl May 27 at 10:58

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.