Since you have time in the file name, use it in time to remove this code that does this:
This script gets the current time in seconds from the era, and then calculates the timestamp 7 days ago. Then, for each file, the file name is analyzed and the date embedded in each file name is converted to a time stamp, then the time stamp is compared to determine which files to delete. Using timestamps gets rid of all the troubles when working with dates directly (leap year, different days in months, etc.)
The actual deletion is commented out so you can verify the code.
#funciton to get timestamp X days prior to input timestamp # arg1 = number of days past input timestamp # arg2 = timestamp ( eg 1324505111 ) seconds past epoch getTimestampDaysInPast () { daysinpast=$1 seconds=$2 while [ $daysinpast -gt 0 ] ; do daysinpast=`expr $daysinpast - 1` seconds=`expr $seconds - 86400` done # make midnight mod=`expr $seconds % 86400` seconds=`expr $seconds - $mod` echo $seconds } # get current time in seconds since epoch getCurrentTime() { echo `date +"%s"` } # parse format and convert time to timestamp # eg 2011-12-23 -> 1324505111 # arg1 = filename with date string in format %Y-%m-%d getFileTimestamp () { filename=$1 date=`echo $filename | sed "s/[^0-9\-]*\([0-9\-]*\).*/\1/g"` ts=`date -d $date | date +"%s"` echo $ts } ########################### MAIN ############################ # Expect directory where files are to be deleted to be first # arg on commandline. If not provided then use current working # directory FILEDIR=`pwd` if [ $# -gt 0 ] ; then FILEDIR=$1 fi cd $FILEDIR now=`getCurrentTime` mustBeBefore=`getTimestampDaysInPast 7 $now` SAVEIFS=$IFS # need this to loop around spaces with filenames IFS=$(echo -en "\n\b") # for safety change this glob to something more restrictive for f in * ; do filetime=`getFileTimestamp $f` echo "$filetime lt $mustBeBefore" if [ $filetime -lt $mustBeBefore ] ; then # uncomment this when you have tested this on your system echo "rm -f $f" fi done # only need this if you are going to be doing something else IFS=$SAVEIFS
source share