Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Unzipping with 7z.exe

I stumbled across the below line as a means of extracting every .zip file in every subfolder.

FOR /F "usebackq" %a in (`DIR /s /b *.zip`) do 7z.exe e %a

I've tried this on a WinXP cmd.exe prompt and I get the error:

"a was unexpected at this time."

Can somebody please tell me whats wrong with the above line. Is this a 7z.exe error or is there something wrong with the batch script syntax. I did cut and paste this into a .bat file.

Cheers

like image 212
SparkyNZ Avatar asked Jan 23 '12 17:01

SparkyNZ


2 Answers

Try to change %a with %%a:

FOR /F "usebackq" %%a in (`DIR /s /b *.zip`) do 7z.exe e %%a
like image 86
Marco Avatar answered Sep 29 '22 10:09

Marco


Building on @PA.'s answer (remember to remove the @echo when you've verified that the output is what you want), if you want to preserve the directory structure inside the zip file, use the x command instead of e:

FOR /R %a IN (*.zip) DO @echo 7z x "%a"

And if you want to extract the files into a folder with the same name as their respective zip file, use the -o switch and the %~n filename extractor prefix:

FOR /R %a IN (*.zip) DO @echo 7z x "%a" -o"%~na"

Finally, if you want to do all of the above and overwrite any existing files, use the -aoa switch:

FOR /R %a IN (*.zip) DO @echo 7z x "%a" -o"%~na" -aoa

Helpful resources

  • http://www.dotnetperls.com/7-zip-examples

Batch file

Here it is, all condensed. The following is a batch script that will work for all zip files in the current folder (assuming 7zip is installed). It defaults to echoing what commands would run and only runs when you pass in /y (as in, yes, please do the unzipping now).

:: To actually include the path expansion character (tilde), I had to give valid numbers; see http://ss64.com/nt/rem.html for bug reference. Also, try call /? for more info.
@REM The %~n0 extracts the name sans extension to use as output folder. If you need full paths, use "%~dpn0". The -y forces overwriting by saying yes to everything. Or use -aoa to overwrite.
@REM Using `x` instead of `e` maintains dir structure (usually what we want)

@FOR /R %%a IN (*.zip) DO @(
    @if [%1] EQU [/y] (
        @7z x "%%a" -o"%%~dpna" -aoa
    ) else (
        @echo 7z x "%%a" -o"%%~dpna" -aoa
    )
)

@echo USAGE: Use /y to actually do the extraction
like image 31
Pat Avatar answered Sep 29 '22 11:09

Pat