We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now


remove old date by shell script

emlily asked
Medium Priority
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 file.zip.200306. and will keep the file.zip.270306 and file.zip.230306

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


ls -t /folder/file.zip.* | sed 1,2d | while read file ; do
         rm $file
Watch Question

Artysystem administrator
Top Expert 2007

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

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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Artysystem administrator
Top Expert 2007

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.
Gabriel OrozcoSolution Architect

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.

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.