Delete all files except the newest 3 in bash script

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

    This will list all files except the newest three:

    ls -t | tail -n +4
    

    This will delete those files:

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

    This will also list dotfiles:

    ls -At | tail -n +4
    

    and delete with dotfiles:

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

    But beware: parsing ls can be dangerous when the filenames contain funny characters like newlines or spaces. If you are certain that your filenames do not contain funny characters then parsing ls is quite safe, even more so if it is a one time only script.

    If you are developing a script for repeated use then you should most certainly not parse the output of ls and use the methods described here: http://mywiki.wooledge.org/ParsingLs

提交回复
热议问题