Script to remove all, BUT retain one latest backup file of all sub-directories

bashshell-script

The following script works for single folder, but I want to iterate through all subdirectories.

ls /home/user/Desktop/cron_database_hourly/*/*_[012][0-9]*.zip | head -n -1 | \
   while read -r f; do rm "$f"; done

Best Answer

You could probably get away with something like (untested) -

for each in `find -type d /home/usr/Desktop/cron_database/hourly`
do
   ls -t $each/_[012][0-9]*.zip | head -n -1 | \ while read -r f; 
       do 
           rm "$f" 
      done
done

the "for each" will loop will find a list of all directories, and adding a "-t" to ls will cause it to sort in date order - with most recent first.

Related Question