Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Keep only last 3 versions of a file

 
Timmy Gupta
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tar files get stored in a directory with name in the following format

<file>21Jun0922:19:46.tar.gz

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?
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18002
47
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic