How can I unzip the newest file in a directory in a .bat file?

I am working on a build system. The build system publishes the results as a zip file in a directory. Unfortunately, I have no easy way to find out the name of a zip file, because it has a timestamp. For the next operation, I have to unzip this zip file to some specific place, and then do some more file operations.

I assume that I can change the build system, so I specify the name of the zip file of the result from the command line, however, although it may be easiest for me to find out which one is the newest file, and unzip it (if the previous process is successful).

How can I execute the unzip command, which will act only on the newest zip file in the directory, ignoring all the others?

EDIT: Instead, I decided to use the ANT features for this task. However, it is still a neat trick to have a true one ... Thanks for the answer!

+3
source share
4 answers

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 the "bare" format - that is, only the name.
  • FOR /F usebackq used to loop output the output of a command.
  • && GOTO DONE || GOTO DONEensures that it UNZIPruns only for the first file. You need both &&(and) and ||(or) if for some reason it is unpacked.

You will need to change UNZIP %%ifor any unzip command that you want to use.

, Zip . , :

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

:

  • "tokens = *" , .

  • , UNZIP,

  • DIR, "usebackq".

+10

Cygwin Unix-

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

+2

, 7-zip, script /.

-1

bat, PowerShell ?

-2

Source: https://habr.com/ru/post/1697991/


All Articles