简体   繁体   中英

bash script to recursively delete files from folders which end in even numbers

I have a nested folder hierarchy containing hundreds of files in the format [az].[0-9].h5

where [az] can be any length alphanumeric, [0-9] can be any number of digits but always a number, and the extension is fixed, h5.

eg

  • model1_weights.1.h5
  • model354_weights.64.h5

etc.

To save space I'd like to delete all of the EVEN files

eg these remain:

  • model1_weights.1.h5
  • model1_weights.37.h5
  • model1_weights.185.h5

but these go

  • model1_weights.0.h5
  • model1_weights.32.h5
  • model1_weights.184.h5

I know how to do this in python, traverse all the directories, split at the dots, check, and delete. But I feel like this should be possible with a single bash command with rm -rf (or find) and regex. Is this possible?

NOTE: In the future to save even more space I may like to delete every 2 out of 3 files. ie general pattern is KEEP only if (i % n ==1) where i is the index of the file, and n is an arbitrary number (eg 2 or 3)

You should be able to use something like this:

shopt -s globstar failglob
rm -rf **/model*_weights.*{0,2,4,6,8}.h5

I would change rm -rf to echo before you run it! Alternatively, printf '%s\\n' would give a clearer output.

The shell option globstar allows you to use ** to do a recursive match. failglob ensures that the command isn't run if nothing matches the pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM