Delete all files except the newest 3 in bash script

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

    Recursive script with arbitrary num of files to keep per-directory

    Also handles files/dirs with spaces, newlines and other odd characters

    #!/bin/bash
    if (( $# != 2 )); then
      echo "Usage: $0  "
      exit
    fi
    
    while IFS= read -r -d $'\0' dir; do
      # Find the nth oldest file
      nthOldest=$(find "$dir" -maxdepth 1 -type f -printf '%T@\0%p\n' | sort -t '\0' -rg \
        | awk -F '\0' -v num="$2" 'NR==num+1{print $2}')
    
      if [[ -f "$nthOldest" ]]; then
        find "$dir" -maxdepth 1 -type f ! -newer "$nthOldest" -exec rm {} +
      fi
    done < <(find "$1" -type d -print0)
    

    Proof of concept

    $ tree test/
    test/
    ├── sub1
    │   ├── sub1_0_days_old.txt
    │   ├── sub1_1_days_old.txt
    │   ├── sub1_2_days_old.txt
    │   ├── sub1_3_days_old.txt
    │   └── sub1\ 4\ days\ old\ with\ spaces.txt
    ├── sub2\ with\ spaces
    │   ├── sub2_0_days_old.txt
    │   ├── sub2_1_days_old.txt
    │   ├── sub2_2_days_old.txt
    │   └── sub2\ 3\ days\ old\ with\ spaces.txt
    └── tld_0_days_old.txt
    
    2 directories, 10 files
    $ ./keepNewest.sh test/ 2
    $ tree test/
    test/
    ├── sub1
    │   ├── sub1_0_days_old.txt
    │   └── sub1_1_days_old.txt
    ├── sub2\ with\ spaces
    │   ├── sub2_0_days_old.txt
    │   └── sub2_1_days_old.txt
    └── tld_0_days_old.txt
    
    2 directories, 5 files
    

提交回复
热议问题