remove old date by shell script

Posted on 2006-03-26
Last Modified: 2010-04-20
the file in the backup as below:

i need to create a script where to keep only the latest 2 file date. example from above the script will remove and will keep the and

Part of my script...the is in the /folder and backup folder is at /folder/backup. My script purposes is....move the in folder directory then change the name to


ls -t /folder/* | sed 1,2d | while read file ; do
         rm $file
Question by:emlily
    LVL 27

    Expert Comment

    change your extention to file.YYMMDD it will be much easier to sort and to find the latest 2
    LVL 19

    Accepted Solution


    it's kind of easy if your files are created on the same date they show.
    because you can use the date the file was created to process it.

    the follow find command deletes all files more than two days old:

    find /folder -type f -mtime +2 -exec rm -fr {} \;

    so you can modify the "+2" part if you want to delete files with more than, say; 4 days old:

    find /folder -type f -mtime +4 -exec rm -fr {} \;

    keep in mind the path should be exactly given, or you will delete all your files!!!!

    Hope this help
    LVL 27

    Expert Comment

    Redimido, when user hasn't run rotation script for last two days (suppose system was down),
    your script will remove all files and will not leave the latest two.
    LVL 19

    Expert Comment

    Nopius: Yes, and that's good enough if you want to have the last 'n' days instead of the last 'n' logs.

    if the system was down, well, then it was down. no further problem.
    if the user forgot to run the rotation script, so then it will not run this script neither.


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    rdate is a Linux command and the network time protocol for immediate date and time setup from another machine. The clocks are synchronized by entering rdate with the -s switch (command without switch just checks the time but does not set anything). …
    The purpose of this article is to demonstrate how we can use conditional statements using Python.
    Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now