Delete all files except the newest 3 in bash script

前端 未结 11 1436
情深已故
情深已故 2020-12-05 18:06

Question: How do you delete all files in a directory except the newest 3?

Finding the newest 3 files is simple:

ls -t | head -3
         


        
11条回答
  •  独厮守ぢ
    2020-12-05 18:28

    As an extension to the answer by flohail. If you want to remove all folders except the newest three folders use the following:

    find . -maxdepth 1 -mindepth 1 -type d -printf '%T@\t%p\n' |
     sort -t $'\t' -g | 
     head -n -3 | 
     cut -d $'\t' -f 2- |
     xargs rm -rf
    

    The -mindepth 1 will ignore the parent folder and -maxdepth 1 subfolders.

提交回复
热议问题