please simplify - ksh delete all files except first one per 7 days period, and give count

StackOverflow https://stackoverflow.com/questions/21877166

  •  13-10-2022
  •  | 
  •  

Question

I want to delete all files in directory $fdir, except the first one, for each 7 days time period.

Then, I want to report how many files were deleted.

I came up with following:

days=365
fcount=0

while (( days > 7 ));do

  # Get all files grouped per week, remove all except the first one.
  fcountnw=$(
    find $fdir -name '*.log' \
      -mtime -$(( days )) \
        -mtime +$(( days - 8 )) \
          -printf "%C@ %p\n" | 
    sort | cut -f2 -d " " | 
      tail -n+2 | xargs rm 2>/dev/null && echo '.' | wc -c
  )
  fcount=$(( fcount+ fcountnw))

  (( days = days - 7 ))

done
echo $fcount

However, find seems to be quite slow. I know exactly in which directory to be, so it possible to do this in a simpler way - e.g. use ls instead?

Any input welcome!!

Was it helpful?

Solution

Why not combine ls with find to eliminate your sort and use an inner while loop instead of xargs

find $fdir -name '*.log' \
    -mtime -$(( days )) \
        -mtime +$(( days - 8 )) \
            -exec ls -1rt {} + |
    tail -n+2 | while read f; do
        rm $f 2>/dev/null
        fcount=$(( fcount + 1 ))
    done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top