How to zip a bunch of files separately with batch commands

You have lots of files on a directory and needs each one of them on a compressed zip file? Easy!

First, install 7-zip. It’s a nice piece of software, an fast and free compressor. It’s what I use. You can use other softwares if you know their DOS commands though.

Then, make a batch file with the following commands:

@echo off
for /r %%X in (*) do (
"C:\Program Files\7-Zip\7z.exe" a "%%~nX.zip" "%%X"
del "%%X"
)

What each of these things do?

The @ symbol at the start of a batch command hides the command itself. Echo off hides all commands from then on. It’s just so there isn’t a lot of commands on the prompt window. Not really necessary but always nice to have.

For command is really interesting. Here, it’s looking for all files in the directory (with the command /r and the selector *), putting each file on a variable called %%X, and running the command after do. You can know more how it works here. There’s one %%~nX in there that it’s the file name without the extension. You can know more about it here.

I put the command in parenthesis so I can run two commands at once: one it’s 7-zip.exe on it’s installation folder, with the arguments to create a zip file for each file (you can make .7z files by replacing the .zip extension). The other one is to delete the file, so only the zipped one stays.

Just open a folder with the files you wanna compress, copy the batch file there, type “cmd” on the folder address to quickly open a cmd window there (did you know that shortcut? Now you do.) and run the batch file. Or just double-click the batch file.

Attention! The program is not very smart and will compress the batch file too. 😛

Leave a Reply