Batch file trickery: finding the first file from a list in a certain directory
Posted by jpluimers on 2010/09/14
Using the Windows command shell, I recently needed a batch file that operated on the first occurrence of a file in a certain directory, where the filename was dynamically obtained from a list.
Wait: that sounds too complex; lets make this clear with an example.
- The batch-file has to process one file per iteration
- The IDs and order of the files is can process are stored in a file called IDs.txt
- The source of the files is the directory queue
- The files need to be processed in a directory processing
- The destination of the files is in the directory done
File: IDs.txt:
1
2
3
4
5
6
7
8
Directory queue:
file-4.txt
file-5.txt
file-6.txt
file-7.txt
So:
The first time the batch file starts, it needs to take file-4.txt, move it to the directory processing, process it, then move it to the directory done.
The second time the batch file starts, it needs to take file-5.txt, move it to the directory processing, process it, then move it to the directory done.
I got into overly complex solutions with call, for, exit, etc. None of them worked very well.
The actual solution needs a few things, so first I’ll show the batch-file, and then I’ll explain the details.
@echo off for /f %%i in (IDs.txt) do if exist queue\file-%%i.sql set ID=%%i& goto :process-one goto :exit :process-one set scriptfile=queue\file-%ID%.txt if not exist %scriptfile% goto :exit move %scriptfile% process\ set scriptfile=process\file-%ID%.txt notepad %scriptfile% move %scriptfile% done\ :exit
Tricks used
The first trick used is the /F in the for command.
It makes the for statement parse the file IDs.txt line by line, and on each line fill the the variable %%i with the first blank separated token on that line, then execute the part after the do.
There are many more options you can include with /F (the link above explains them), but this suffices for my solution.
The second trick is to use the ampersand (&) to execute two commands on one line.
I need the contents of %%i outside of the loop, but when you do only a goto, you loose the contents of %%i (as it is not valid outside of the loop).
This is explained in the Using multiple commands and conditional processing symbols section of Command shell overview.
Note that you should avoid the space in front of the &, otherwise the batch-file will try to process file-4 .txt and file-5 .txt (since then a space gets appended to %ID%).
More batch-file trickery in the future :-)
–jeroen






Leave a comment