Delete all files except the newest 3 in bash script

前端 未结 11 1450
情深已故
情深已故 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:37

    ls -t | tail -n +4 | xargs -I {} rm {}
    

    Michael Ballent's answer works best as

    ls -t | tail -n +4 | xargs rm --
    

    throw me error if I have less than 3 file

提交回复
热议问题