Delete all files except the newest 3 in bash script

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

    Solution without problems with "ls" (strange named files)

    This is a combination of ceving's and anubhava's answer. Both solutions are not working for me. Because I was looking for a script that should run every day for backing up files in an archive, I wanted to avoid problems with ls (someone could have saved some funny named file in my backup folder). So I modified the mentioned solutions to fit my needs. Ceving's solution deletes the three newest files - not what I needed and was asked.

    My solution deletes all files, except the three newest files.

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

    Some explanation:

    find lists all files (not directories) in current folder. They are printed out with timestamps.
    sort sorts the lines based on timestamp (oldest on top).
    head prints out the top lines, up to the last 3 lines.
    cut removes the timestamps.
    xargs runs rm for every selected file.

    For you to verify my solution:

    (
    touch -d "6 days ago" test_6_days_old
    touch -d "7 days ago" test_7_days_old
    touch -d "8 days ago" test_8_days_old
    touch -d "9 days ago" test_9_days_old
    touch -d "10 days ago" test_10_days_old
    )
    

    This creates 5 files with different timestamps in the current folder. Run this script first and then the code for deleting old files.

提交回复
热议问题