Friday, August 27, 2010

The ultimate one-liner to ZIP a bunch of different directories up into separate files...

Suppose you have a bunch of directories that you want to ZIP up, each having individual ZIP files. You also want to collapse any subdirectories within those directories.

This blog entry says to never use ls and pipe it to awk. The reason? If you have any directories that have spaces in them, awk will not parse them correctly. For more info, see here:

http://stackoverflow.com/questions/1447809/awk-print-9-the-last-ls-l-column-including-any-spaces-in-the-file-name

Eventually, I settled on this line:
find . -maxdepth 1 -type d -print | awk '{if ($0 == ".") next; print "zip -r -j \""$0".zip\" \""$0"\""}' | sh
The "-type d" means to search for only directories. I pipe the result to awk, which skips the listing if it's a "." directory listing. Notice also I use $0 with awk -- since the default delimeter is a space, any directories with spaces will get parsed into $1.

I use the "-r" option to scan the directories recursively and the "-j" to junk the directory name.
In addition, I add surrounding quotation marks for both the zip file and directory (\") to avoid Unix parsing issues (in case the directories have spaces in them).

I then pipe the final result to 'sh', which will execute the statement.

If you're in doubt, you can remove the final sh pipe ("| sh") to see how this command works for you!

No comments:

Post a Comment