Friday, January 13, 2012

Linux Zip Multiple File by Batch

Situation:

The other day, I found myself cleaning up backup files of one of the server Iam handling, which was turnover to me about 3 months ago. the server is cluttered with lots of 500MB file which is folder by month and filed by date. this files is a sql dump from postgres DB. I need to compress them for archives. such each folder ex. January contains 60 files per day AM and PM. as
  • January
    • 2010-01-01AM.sql
    • 2010-01-01PM.sql
    • 2010-01-02AM.sql
    • 2010-01-02PM.sql 
    • ... 
I need to compress this 1 by 1 so it is a lot of pain. and I found this script in the net cant remember where but modifying it a bit it proves very helpful.

Compress Files by Batch in the Folder

$> for f in *; do zip "$f".zip "$f"; done

a little explanation

1. for f in *; do  
2.    zip "$f".zip "$f";
3. done

  • 1st part will say to do a loop for each f in * - signify the list of files when you do an ls on a directory. hence giving you a list of of your files, each file name will be put in a variable "f" so looping for eah file name do #2
  • 2nd part will do a command gzip "$f".zip "$f" which is equivalent to "gzip filename.ext.zip filename.ext"
  • last part signify the end of the loop.
you can also do a nested loop for processing directory. I have done that myself, I hope this would help somebody.

Thanks for reading.



No comments:

Post a Comment