FOR
suggest changeIterates 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 each line in a file, echoes the line.
for /f "tokens=*" %i in (list1.txt list2.txt) do @echo %i
- For each line in the files, echoes the line.
for /f "tokens=*" %i in (*.txt) do @echo %i
- Does nothing. Does not accept wildcards to match file names.
for /f "tokens=1-3 delims=:" %a in ("First:Second::Third") do @echo %c-%b-%a
- Parses a string into tokens delimited by
:
. - The quotation marks indicate the string is not a file name.
- The second and third tokens are stored in
%b
and%c
even though%b
and%c
are not expressly mentioned in the part of the command before "do". - The two consecutive colons are treated as one separator;
%c
is not "" but rather "Third". - Does some of the job of the cut command from other operating systems.
- Parses a string into tokens delimited by
for /f "tokens=1-3* delims=:" %a in ("First:Second::Third:Fourth:Fifth") do @echo %c-%b-%a: %d
- As above, just that the 4th and 5th items get captured in
%d
as "Fourth:Fifth", including the separator.
- As above, just that the 4th and 5th items get captured in
for /f "tokens=1-3* delims=:," %a in ("First,Second,:Third:Fourth:Fifth") do @echo %c-%b-%a: %d
- Multiple delimiters are possible.
for /f "tokens=1-3" %a in ("First Second Third,item") do @echo %c-%b-%a
- The default delimiters are space and tab. Thus, they differ from the separators used to separate arguments passed to a batch.
for /f "tokens=*" %i in ('cd') do @echo %i
- For each line of the result of a command, echoes the line.
for /f "tokens=*" %i in ('dir /b /a-d-h') do @echo %~nxai
- For each non-hidden file in the current folder, displays the file attributes followed by the file name. In the string
%~nxai
, uses the syntax described at percent tilde.
- For each non-hidden file in the current folder, displays the file attributes followed by the file name. In the string
for /f "usebackq tokens=*" %i in (`dir /b /a-d-h`) do @echo %~nxai
- As above, but using the back-quote character (
`
) around the command to be executed.
- As above, but using the back-quote character (
for /f "tokens=*" %i in ('tasklist ^| sort ^& echo End') do @echo %i
- Pipes and ampersands in the command to be executed must be escaped using caret (
^
).
- Pipes and ampersands in the command to be executed must be escaped using caret (
(for %i in (1,2,3) do @echo %i) > anyoldtemp.txt
- To redirect the entire result of a for loop, place the entire loop inside brackets before redirecting. Otherwise, the redirection will tie to the body of the loop, so each new iteration of the body of the loop will override the results of the previous iterations.
for %i in (1,2,3) do @echo %i > anyoldtemp.txt
- An example related to the one above. It shows the consequence of failing to put the loop inside brackets.
Continue: To jump to the next iteration of the loop and thus emulate the continue statement known from many languages, you can use goto
provided you put the loop body in a subroutine, as shown in the following:
for %%i in (a b c) do call :for_body %%i
exit /b
:for_body
echo 1 %1
goto :cont
echo 2 %1
:cont
exit /b
If you use goto
directly inside the for loop, the use of goto
breaks the loop bookkeeping. The following fails:
for %%i in (a b c) do (
echo 1 %%i
goto :cont
echo 2 %%i
:cont
echo 3 %%i
)
Links:
$ for /?
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.
If Command Extensions are enabled, the following additional
forms of the FOR command are supported:
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
generate the sequence (5 4 3 2 1)
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
or, if usebackq option present:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
file-set is one or more file names. Each file is opened, read
and processed before going on to the next file in file-set.
Processing consists of reading in the file, breaking it up into
individual lines of text and then parsing each line into zero or
more tokens. The body of the for loop is then called with the
variable value(s) set to the found token string(s). By default, /F
passes the first blank separated token from each line of each file.
Blank lines are skipped. You can override the default parsing
behavior by specifying the optional "options" parameter. This
is a quoted string which contains one or more keywords to specify
different parsing options. The keywords are:
eol=c - specifies an end of line comment character
(just one)
skip=n - specifies the number of lines to skip at the
beginning of the file.
delims=xxx - specifies a delimiter set. This replaces the
default delimiter set of space and tab.
tokens=x,y,m-n - specifies which tokens from each line are to
be passed to the for body for each iteration.
This will cause additional variable names to
be allocated. The m-n form is a range,
specifying the mth through the nth tokens. If
the last character in the tokens= string is an
asterisk, then an additional variable is
allocated and receives the remaining text on
the line after the last token parsed.
usebackq - specifies that the new semantics are in force,
where a back quoted string is executed as a
command and a single quoted string is a
literal string command and allows the use of
double quotes to quote file names in
file-set.
Some examples might help:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with
a semicolon, passing the 2nd and 3rd token from each line to the for
body, with tokens delimited by commas and/or spaces. Notice the for
body statements reference %i to get the 2nd token, %j to get the
3rd token, and %k to get all remaining tokens after the 3rd. For
file names that contain spaces, you need to quote the filenames with
double quotes. In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.
%i is explicitly declared in the for statement and the %j and %k
are implicitly declared via the tokens= option. You can specify up
to 26 tokens via the tokens= line, provided it does not cause an
attempt to declare a variable higher than the letter 'z' or 'Z'.
Remember, FOR variables are single-letter, case sensitive, global,
and you can't have more than 52 total active at any one time.
You can also use the FOR /F parsing logic on an immediate string, by
making the file-set between the parenthesis a quoted string,
using single quote characters. It will be treated as a single line
of input from a file and parsed.
Finally, you can use the FOR /F command to parse the output of a
command. You do this by making the file-set between the
parenthesis a back quoted string. It will be treated as a command
line, which is passed to a child CMD.EXE and the output is captured
into memory and parsed as if it was a file. So the following
example:
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
would enumerate the environment variable names in the current
environment.
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
environment variable for %I and expands to the
drive letter and path of the first one found.
%~ftzaI - expands %I to a DIR like output line
In the above examples %I and PATH can be replaced by other valid
values. The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.