Handy Windows one-liner: Batch processing via DOS FOR command


Mostly when prototyping or measuring performance I have to run an application or two over a large set of files. Adding a support for batch processing for such little things isn’t something I’d want to waste my time on. Particularly when I’m running short on time, which is, unfortunately how most of the time is.

For once, just this once, I’m going to say that Windows’ command-line interface isn’t really as bad as people make it out to be. The crowning glory being the swiss-army knife otherwise known as FOR. Really, if you don’t go through the documentation, you wouldn’t know what you’re missing. But here’s a little taste of what it can do:

Suppose, I have an executable called wdp2tif (yeah, something I wrote) which takes an input filename (as argv[ 1 ]) and an output filename (as argv[ 2 ]) and I need to run this over a set of about 700 odd WDP (or HDPhoto as it was known back in the day) image files tucked in some obscure directory of the filesystem. I’d also want the output to be created in a specific folder and each output file to keep the same name as the corresponding input file but with a different extension. All that is yours for free only if you were to invoke this little piece of magic:

for /R wdp %v in (*) do Debug\wdp2tif.exe %v %CD%\tif\%~nv.tif

So, what’s going on here? Let’s take this bit by bit. I’ll color code the parts as follows: for syntax/switches, variables used within the execution of the for command, environment (aka special) variablesĀ  andĀ  string operations.

for /R wdp %v in (*) do Debug\wdp2tif.exe %v %CD%\tif\%~nv.tif

The /R switch tells for to run recursively, beginning with the directory mentioned immediately to the right (wdp in our case), and for every item matching the pattern (* in our case matches every single file) specified in the set (delimited by the parentheses) it executes the action sequence following the keyword do. In our case, the action sequence is simple, it runs the executable called wdp2tif.exe found in the Debug folder under the current directory passing in the current file (saved in our variable %v) as input and creating an output filename using a special string operations that for provides. The ~n tells for to strip everything from the full path but the filename and then applies it to the %v variable and concatenates the `.tif` bit at the end. And voila!

Remember, if you want this to be in a batch file of its own, you need to escape the variables, so prepend a % before the variable instance as follows:

Testrunner.bat

————8<——————————————8<——————-

@echo off

REM convert all WDP images in the ‘wdp’ folder to tiff

REM and place them in a ‘tif’ folder

REM TODO generalize for application name, search start folder and destination folder

for /R wdp %%v in (*) do Debug\wdp2tif.exe %%v %CD%\tif\%%~nv.tif

————8<——————————————8<——————-

About these ads

About this entry