-
Syntax Purpose FOR %%A IN (...) DOLoop over a set of items/files FOR /L %%A IN (start,step,end) DOLoop through numeric ranges FOR /F %%A IN (...) DOLoop through text files or command output
-
FOR %%A IN (item1 item2 item3) DO ( ECHO Item: %%A )
-
FOR %%F IN (*.txt) DO ( ECHO Found text file: %%F )
- Wildcards like
*and?are supported. - Double percent (
%%) is used in batch files. In the command line, use single%.
- Wildcards like
-
This variant is similar to traditional C-style loops.
FOR /L %%I IN (1,1,5) DO ( ECHO Count: %%I )
(1,1,5)means start at 1, increment by 1, until 5.- You can count down too:
FOR /L %%I IN (5,-1,1) DO ( ECHO Reverse Count: %%I )
-
Processes contents from:
- A file
- A string
- The output of a command
FOR /F "tokens=1,2 delims=," %%A IN (data.csv) DO ( ECHO Name: %%A, Age: %%B )
Options:
tokens=n: Select which fields (words) to parse.delims=,: Define delimiter character.skip=n: Skip header lines.
FOR /F %%A IN ('DIR /B *.txt') DO ( ECHO File: %%A )
FOR %%I IN (A B) DO ( FOR %%J IN (1 2) DO ( ECHO %%I %%J ) )
-
Always double the
%sign in batch files (%%A). -
Wrap variables in quotes to handle spaces.
-
When reading from command output,
FOR /Ftrims whitespace by default.To preserve spacing and empty lines, use
usebackqanddelims=.FOR /F "usebackq delims=" %%L IN ("my file.txt") DO ( ECHO Line: %%L )
-
Rename All
.logto.bakFOR %%F IN (*.log) DO ( REN "%%F" "%%~nF.bak" )
-
Read IPs from File and Ping
FOR /F %%I IN (ips.txt) DO ( PING -n 1 %%I )
| Type | Example | Use Case |
|---|---|---|
| File loop | FOR %%F IN (*.txt) |
Process file list |
| Number loop | FOR /L %%I IN (1,1,5) |
Count or iterate numerically |
| Text loop | FOR /F %%L IN (file.txt) |
Read lines or command output |