2

lets say I have a my_dirs/ directory, insdie that directory I have several parallel subdirectories which has several files and I want to delete all of them except the ones that have the substring '.regions'

this is my parent directory content: enter image description here

this is what I tried:

shopt -s extglob

rm -r !(./**/*.regions*)

but I got an error message: cannot be deleted «! (./**/*. region *) »: The file or directory does not exist.

how can I do that?

Valentin
  • 399
  • 2
  • 10

1 Answers1

4

First of all, always be careful when deleting multiple files. The command to achieve what you want would be:

find my_dirs -type f ! -name "*.regions*" -delete

"-delete" must be last, otherwise it will delete everything it finds

This will explore all subdirectories in my_dirs, find the files (-type f) that not (!) contain ".regions" ("*.regions*") on their name, and delete (-delete) them.

I recommend running this first: find my_dirs -type f ! -name "*.regions*", so it won't delete anything and you can check the files are correct.

Edit: Added -type f so it only targets files per Philippe's suggestion.