Delete all files except the newest 3 in bash script

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

    This uses find instead of ls with a Schwartzian transform.

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

    find searches the files and decorates them with a time stamp and uses the tabulator to separate the two values. sort splits the input by the tabulator and performs a general numeric sort, which sorts floating point numbers correctly. tail should be obvious and cut undecorates.

    The problem with decorations in general is to find a suitable delimiter, which is not part of the input, the file names. This answer uses the NULL character.

提交回复
热议问题