[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 313
  • Last Modified:

remove old date by shell script

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
  • 2
  • 2
1 Solution
change your extention to file.YYMMDD it will be much easier to sort and to find the latest 2
Gabriel OrozcoSolution ArchitectCommented:

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
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 ArchitectCommented:
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now