user3596788
user3596788

Reputation: 95

Batch script to zip like files using wildcard

I have a folder with 600 text files, I'm looking to zip together files with similar identifiers. So for instance I have 10 files with id001~ as the identifier, those 10 will be zipped in the same directory and so forth. So far I have a code that will zip 1 file when you hard code the file name. I'm not sure if this should read off a list or maybe specify some type of wildcard criteria for which files to zip

Any help is greatly appreciated.

echo off
set archievePatch=id001~testfile3.txt
7z.exe a %archievepatch%.zip "%archievePatch%" 

PATH :\Users\Jeffery\Desktop\TestFolder
pause
exit

This will output a zip file named: id001~testfile3.zip

Upvotes: 1

Views: 1529

Answers (1)

KennyBOT
KennyBOT

Reputation: 447

Based on that one sample of how your filename looks like the following script would group all files together in a zip file as long as the first 5 characters are equal.

for /f %%f in ('dir /b /on *.txt') do call :onefile %%f

goto :eof

:onefile
set arg1=%1

rem here is the number of characters configured that form a group
set grp=%arg1:~0,5%

call :zipit %arg1% %grp%
goto :EOF

:zipit
rem remove echo when done debugging
echo 7z.exe a "%2.zip" "%1"
goto :EOF

This would create a file id001.zip with all files that start with id001 like id001~testfile3.txt etc.

How does this work?

From the help set (or SET /?) pages:

...
May also specify substrings for an expansion.
%PATH:~10,5%
would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result. If the length is not specified, then it defaults to the remainder of the variable value.
...

The dir command accepts a /b argument to list files in bare-format and /o let you specify an order, the n means order alphabetically on filename.

Upvotes: 1

Related Questions