Page 1 of 1

Help with long filenames in batch loop

Posted: 19 May 2010 14:13
by stugreene
I want to create a batch file to zip several files into separate archive files.

The files in question look like:
weekly status update 20080229.xls
weekly status update 20080321.xls
etc.

I want to preserve the long filename but just make it a .zip file

my batch file reads:
for /f %%a in ('dir /b "weekly status update*.*"') do zip %%~na.zip %%a

The problem is that %%a is being set to "weekly", i.e. it is only getting up to the first space in the long filename. I can test this by changing the command to read:
do echo %%a

Everything I've read says that as long as I enclose the long filename in double-quotes it should be fine, so what am I missing? I'm using XP, start/run/cmd

Thanks,
Stu Greene

Re: Help with long filenames in batch loop

Posted: 19 May 2010 15:33
by Graffic
I'm a total noob (in fact I just made my first post and it's also a question) but I think this will do what you need it to do, or at least get you going in the right direction:

Code: Select all

for %%a in ("weekly*.*") do zip "%%a" "%%~na.zip"

Part of the problem is that the last two arguments were reversed and they need to be in quotes too since you're dealing with the same long filenames there..

I hope it's of some help.

graf

Re: Help with long filenames in batch loop

Posted: 19 May 2010 15:53
by stugreene
Thanks for the reply, but when I do that:
for %%a in ("weekly status update*.*") do zip "%%a" "%%~na.zip"

I get:
zip "weekly" "weekly.zip"
zip warning: name not matched: weekly.zip

If I leave off the double-quotes in the do command, I get:
zip weekly weekly.zip

the problem appears to be in assigning the long filename to the %%a variable - I'm only getting the first word.

PS - the destination archive file does come first in the zip command

Re: Help with long filenames in batch loop

Posted: 19 May 2010 16:02
by Graffic
Hmm.. sorry. :(

And yeah, you're right.. it's been a long time since I've used command line zip, hehehe.

graf

Re: Help with long filenames in batch loop

Posted: 19 May 2010 16:08
by aGerman
I'm not familar with the syntax of zip, but using quots is the right way.
try
[EDIT You have to replace the standard delimiter by "nothing"]

Code: Select all

for /f "delims=" %%a in ('dir /a-d /b "weekly status update*.*"') do zip "%%~na.zip" "%%a"


Regards
aGerman

Re: Help with long filenames in batch loop

Posted: 20 May 2010 07:12
by stugreene
aGerman,

Thanks, that worked perfectly!

Re: Help with long filenames in batch loop

Posted: 21 May 2010 08:49
by avery_larry
And for the record -- you have to use the usebackq option in order to use double quotes as part of the filename/wildcard.

Your for command treated "weekly status update*.*" as a STRING, not as a filename/wildcard -- so "weekly" is the first token -> %%a.

Code: Select all

for /f "usebackq" %%a in ("weekly status update*.*") do zip "%%a" "%%~na.zip"