Delete all files except the newest 3 in bash script

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

    The following looks a bit complicated, but is very cautious to be correct, even with unusual or intentionally malicious filenames. Unfortunately, it requires GNU tools:

    count=0
    while IFS= read -r -d ' ' && IFS= read -r -d '' filename; do
      (( ++count > 3 )) && printf '%s\0' "$filename"
    done < <(find . -maxdepth 1 -type f -printf '%T@ %P\0' | sort -g -z) \
         | xargs -0 rm -f --
    

    Explaining how this works:

    • Find emits for each file in the current directory.
    • sort -g -z does a general (floating-point, as opposed to integer) numeric sort based on the first column (times) with the lines separated by NULs.
    • The first read in the while loop strips off the mtime (no longer needed after sort is done).
    • The second read in the while loop reads the filename (running until the NUL).
    • The loop increments, and then checks, a counter; if the counter's state indicates that we're past the initial skipping, then we print the filename, delimited by a NUL.
    • xargs -0 then appends that filename into the argv list it's collecting to invoke rm with.

提交回复
热议问题