简体   繁体   English

bash脚本以递归方式从文件夹中删除以偶数结尾的文件

[英]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 我有一个嵌套的文件夹层次结构,包含数百个格式为[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. 其中[az]可以是任何长度的字母数字,[0-9]可以是任意数量的数字但总是数字,并且扩展名是固定的,h5。

eg 例如

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

etc. 等等

To save space I'd like to delete all of the EVEN files 为了节省空间,我想删除所有EVEN文件

eg these remain: 例如:

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

but these go 但这些都是

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

I know how to do this in python, traverse all the directories, split at the dots, check, and delete. 我知道如何在python中执行此操作,遍历所有目录,分割点,检查和删除。 But I feel like this should be possible with a single bash command with rm -rf (or find) and regex. 但我觉得这应该可以使用rm -rf(或find)和regex的单个bash命令。 Is this possible? 这可能吗?

NOTE: In the future to save even more space I may like to delete every 2 out of 3 files. 注意:将来为了节省更多空间,我可能希望删除3个文件中的每2个。 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) 即,只有当(i%n == 1)其中i是文件的索引时,一般模式才是KEEP,并且n是任意数字(例如2或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! 我会在运行之前将rm -rf更改为echo Alternatively, printf '%s\\n' would give a clearer output. 或者, printf '%s\\n'将提供更清晰的输出。

The shell option globstar allows you to use ** to do a recursive match. shell选项globstar允许您使用**进行递归匹配。 failglob ensures that the command isn't run if nothing matches the pattern. failglob确保在没有与模式匹配的情况下不运行命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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