Purge X old days files and Print count

Hello All,

I am trying to purge X old days of files from directory & Sub directories

./2016-01-13/1500/abc.txt 
./2016-01-14/1605/caf.txt
./2016-01-14/1605/caf2.txt
./2016-01-14/1606/eaf.txt
..... 
./2017-08-1/1701/

Should also remove directories and sub directories too

Expected output:
Should send out an email saying
Purged X days older files with stats like
1(Number of files deleted): 2016-01-13
2 : 2016-01-14

Currently, I got a find commands one tells counts in directories

find -maxdepth 1 -mtime +10 -type d | sort | while read -r dir; do n=$(find "$dir" -type f | wc -l); printf "%4d : %s\n" $n "$dir"; done 

Regards,
Krus

using bash this is one way -- example :

#!/bin/bash
cd /starting/path
find -maxdepth 1 -mtime +10 -type d | sort | 
  while read -r dir
  do 
     n=0
     find "$dir" -type f -exec (( n++ )) -exec rm {} \;
     printf "%4d : %s\n" $n "$dir"
  done   

Thanks, Jim.

     find "$dir" -type f -exec (( n++ )) -exec rm {} \; 

how to test without -exec rm {} ?

Regards,
Karthik

Jim,
find -exec can run shell scripts but not statements of the current shell.

Hi Jim,

#!/bin/bash
cd /starting/path
find -maxdepth 1 -mtime +10 -type d | sort | 
  while read -r dir
  do 
     n=0
     find "$dir" -type f -exec (( n++ )) \; #-exec rm {} \;
     printf "%4d : %s\n" $n "$dir"
  done

Whats wrong in above script?

How to test script without rm command. And if I commented

-exec rm {}

then i'm getting an error. anything i'm missing?

-Krux

Try

-exec echo rm {}
# GNU only
# find . -type d -mindepth 1 -maxdepth 1 -mtime +10 -print
# portable
find . -type d \! -name . -prune -mtime +10 -print | sort |
while read dir
do
  n=$(
    find "$dir" -type f -mtime +10 -exec true rm -f {} \; -print | grep -c .
  )
  if [ $n -gt 0 ]
  then
    echo "$n files deleted in $dir"
  fi
  find "$dir" -depth -type d -empty -exec true rmdir {} \;
  if [ \! -d "$dir" ]
  then
    echo "$dir deleted"
  fi
done

Remove true to really do the deletions.

1 Like

Perfect. Thanks, MadeInGermany.