Batch File Looping
Example
for %%i in (*) do "echo %%~fi" for %%i in (*) do ( echo %%~fi )
Note that in an interactive shell, only one % should be used.
Options
The for command has options that can fundamentally change the execution of the loop.
Option |
Usage |
Description |
/r |
for /r C:\path\to\target\root %%i in (*) do ... |
Recurse over the file tree from a target root |
/d |
for /d %%i in (*) do ... |
Loop over directories only |
/l |
for /l %%i in (1,10,1) do ... |
Iterate over the range (start,stop,step) |
/f |
for /f %%i in ('my-command') do ... |
Loop over the lines of output from a command |
/f |
for /f %%i in (*) do ... |
Loop over the lines of the files in the set |
Sets
The set of files that are looped over (given normal for behavior, or when using one of the /r, /d, or /f options) is controlled by the set. The wildcard set ((*)) includes everything.
To loop only over Microsoft Word files, try:
for %%i in (*.doc *.docx) do ( ... )
Variable Modifiers
The current loop target is stored into the variable named on the for command. In the above examples, this is %%i. (The i can be replaced with any single-letter name.)
Within the context of the loop, there are a number of modifiers available.
Modifer |
Returns |
%%~i |
The target with surrounding quotes stripped |
%%~fi |
The target's absolute path |
%%~di |
The target's drive letter |
%%~pi |
The target's path |
%%~ni |
The target's filename (no file extension) |
%%~xi |
The target's file extension |
%%~ai |
The target's attributes |
%%~ti |
The target's date and time |
%%~zi |
The target's size |
%%~nxi |
The target's filename (with extension) |
Note that the final modifier is a combination of modifiers. These can all be combined as needed. %%~ftzai mimics the output of dir.