Delete all files except the newest 3 in bash script

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

    In zsh:

    rm /files/to/delete/*(Om[1,-4])
    

    If you want to include dotfiles, replace the parenthesized part with (Om[1,-4]D).

    I think this works correctly with arbitrary chars in the filenames (just checked with newline).

    Explanation: The parentheses contain Glob Qualifiers. O means "order by, descending", m means mtime (See man zshexpn for other sorting keys - large manpage; search for "be sorted"). [1,-4] returns only the matches at one-based index 1 to (last + 1 - 4) (note the -4 for deleting all but 3).

提交回复
热议问题