1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Rep Power

    Batch Script-to delete the files which is 1 year older than the current date

    Plz help me anyone to write the batch script

    In batch Script am trying to delete the files which is 1 year older than the current date.

    The files format is: filename_20101030

    In one particular folder all the files will be there the file names are in the above format.

    If i run the script it should take the currentdate and it should go 1 year back and search the files which are older than current date and delete those files.

    Current date :20101031
    1 year back :20091031

    the files which are filename_20090930,filename_20090831...
    all these files should be deleted.
  2. #2
  3. Moderator Emeritus
    Devshed Supreme Being (6500+ posts)

    Join Date
    Feb 2002
    Austin, TX
    Rep Power
    Moved to UNIX from Scripts
    DrGroove, Devshed Moderator | New to Devshed? Read the User Guide | Connect with me on LinkedIn
    The Most Important Article You Can Read as a Developer
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2006
    Rep Power
    If it is based purely on the filename then your best bet is a script that constructs a date comparison variable in form yyyymmdd based on current date, with 1 subtracted from the year (much like the date pattern in the filenames you have, which is handy!) and treat it as a plain number, comparing the date part of the file names to your comparison variable.
    One way to do that is, assuming you are in the correct directory (not tested!):
    yr=$(date "+%Y")
    yr=$(( yr - 1 ))
    mmdd=$(date "+%md")
    for file in $(ls -1)
      date_part=$(echo $file | awk -F_ '{print $2}')
      if [ $date -lt $a_year_ago ]
         echo "Deleting file $file as it is over a year old"
    If it can be based on last modification date then a find using the -mtime +365 option will list files not modified for over a year.
    The moon on the one hand, the dawn on the other:
    The moon is my sister, the dawn is my brother.
    The moon on my left and the dawn on my right.
    My brother, good morning: my sister, good night.
    -- Hilaire Belloc

IMN logo majestic logo threadwatch logo seochat tools logo