views:

945

answers:

4

I am working on a build system. The build system posts the results as a zip file in a directory. Unfortunately I have no easy way to know the name of the zip file, because it is timestamped. For the next operation, I must decompress this zip file to some specific location and then do some more file operations.

I guess I could change the build system so I specify the name of the result zip file from the command line, however, I though it might be easiest just to find out which one is the newest file and unzip it (if the previous process is successful).

How can I issue an unzip command that will only take effect on the newest zip file in the directory, ignoring all others?

EDIT: I decided to use the capabilities in ANT for this task instead. However, it is still a neat trick to have up the sleve... Thanks for the answer!

A: 

Why use bat files when you have powershell or console applications?

Rasmus
A: 

I think you would need 7-zip to be able to script compression/uncompression.

RedWolves
+9  A: 

This should do it:

FOR /F usebackq %%i IN (`DIR /B /O-D *.ZIP`) DO UNZIP %%i && GOTO DONE || GOTO DONE
:DONE

This works as follows:

  • DIR /B /O-D *.ZIP lists all ZIP files in reverse date order in a "bare" - i.e. name only - format.
  • FOR /F usebackq is used to loop over the output of the command.
  • && GOTO DONE || GOTO DONE makes sure the UNZIP is only run for the first file. You need both && (and) and || (or) in case the unzip fails for some reason.

You'll need to change UNZIP %%i for whatever unzip command you want to use.

EDIT The above will work as long as the Zip filename doesn't contain any spaces. If you want to handle filenames with spaces, use the following variant:

FOR /F "tokens=*" %%i IN ('DIR /B /O-D *.ZIP') DO UNZIP "%%i" && GOTO DONE || GOTO DONE
:DONE

The differences are:

  • The "tokens=*" option returns the whole of the filename even if it contains spaces.

  • The filename passed to UNZIP is quoted

  • This variant uses single quotes for the DIR command so doesn't need the "usebackq" option.

Dave Webb
+1  A: 

If Cygwin or other Unix-like environment is an alternative

unzip "$(ls -tr *zip | tail -n1)"

would do it

John Nilsson
You can also download http://unxutils.sourceforge.net/ and add it to your path to let you use a lot of the standard Unix utilities from a command prompt -- a must have on my Windows machines so in case I forget dir vs. ls, cat vs. type, etc. Nice to have grep, awk, and such too.
Randy
Sorry, correcting that last link -- looks like they've moved stuff around and to get the actual files you have to go to http://sourceforge.net/projects/unxutils
Randy