File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Linux / UNIX and the fly likes Keep only last 3 versions of a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » Linux / UNIX
Bookmark "Keep only last 3 versions of a file" Watch "Keep only last 3 versions of a file" New topic

Keep only last 3 versions of a file

Timmy Gupta

Joined: Dec 06, 2008
Posts: 6
Tar files get stored in a directory with name in the following format


I need to write a script which when run should keep only the latest 3 versions of the file and delete the other versions. This could be achieved by reading the date and time form the tar name. But how to determine which ones are the latest 3 versions.

Could anyone please help me regarding the problem?

Think before you speak as you might hurt or break someone's heart.
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 17421

If you can rely on the file's own filesystem date, the output of "ls -l[r]t" can be used. Something like:

ls -lrt | tail -l -3 | xargs rm

WARNING: Major corrections probably required.

I prefer my naming conventions to be more in the line of "fileYYYYMMDD.tar.gz" myself. Not only can you use a simple sort, it avoids confusion about American/English date formats (MM/DD/YY vs. DD/MM/YY) - not to mention other countries. Named months are not well-suited for date arithmetic, even when international issues don't figure in.

An IDE is no substitute for an Intelligent Developer.
I agree. Here's the link:
subject: Keep only last 3 versions of a file
It's not a secret anymore!