Iterates over a series of values, executing a command.
In the following examples, %i
is to be used from the command line while %%i
is to be used from a batch. The index (e.g., %i
) must be a single character variable name.
Examples:
for %%i in (1,2,3) do echo %%i
In a batch, echoes 1, 2, and 3. In a batch, the command must use a double percent sign.
The remaining examples are intended to be directly pasted into a command line, so they use a single percent sign and include @
to prevent repetitive display.
for %i in (1,2,3) do @echo %i
From a command line, echoes 1, 2, and 3.
The for command tries to interpret the items as file names and as patterns of file names containing wildcards.
It does not complain if the items do not match existing file names, though.
for %i in (1,2,a*d*c*e*t) do @echo %i
Unless you happen to have a file matching the third pattern, echoes 1 and 2, discarding the third item.
for %i in (1 2,3;4) do @echo %i
Echoes 1, 2, 3, and 4. Yes, a mixture of item separators is used.
for %i in (*.txt) do @echo %i
Echoes file names of files located in the current folder and having the .txt
extension.
for %i in ("C:\\Windows\\system32\\*.exe") do @echo %i
Echoes file names matching the pattern.
for /r %i in (*.txt) do @echo %i
Echoes file names with full paths, of files having the extension .txt
located anywhere in the current folder including nested folders.
for /d %i in (*) do @echo %i
Echoes the names of all folders in the current folder.
for /r /d %i in (*) do @echo %i
Echoes the names including full paths of all folders in the current folder, including nested folders.
for /r %i in (*) do @if %~zi geq 1000000 echo %~zi %i
For each file in the current folder and its sub-folders that has the size greater than or equal to 1,000,000 bytes, outputs the file size in bytes and the full path of the file. For the syntax in %~zi
, see percent tilde.
for /l %i in (1,1,10) do @echo %i
Echoes the numbers from 1 to 10.
for /f "tokens=*" %i in (list.txt) do @echo %i
for /f "tokens=*" %i in (list1.txt list2.txt) do @echo %i
for /f "tokens=*" %i in (*.txt) do @echo %i
for /f "tokens=1-3 delims=:" %a in ("First:Second::Third") do @echo %c-%b-%a
:
.%b
and %c
even though %b
and %c
are not expressly mentioned in the part of the command before "do".%c
is not "" but rather "Third".for /f "tokens=1-3* delims=:" %a in ("First:Second::Third:Fourth:Fifth") do @echo %c-%b-%a: %d
%d
as "Fourth:Fifth", including the separator.for /f "tokens=1-3* delims=:," %a in ("First,Second,:Third:Fourth:Fifth") do @echo %c-%b-%a: %d