FOR HELP

external links: index. batch. internal links: end

For Runs a specified command for each file in a set of files.

Syntax: for {%variable|%%variable} in (set) do command [ CommandLineOptions]

Parameters:

{%variable|%%variable} Required. Represents a replaceable parameter. Use %variable to carry out for from the command prompt. Use %%variable to carry out the for command within a batch file. Variables are case-sensitive and must be represented with an alpha value, such as %A, %B, or %C.
(set) Required. Specifies one or more files, directories, range of values, or text strings that you want to process with the specified command. The parentheses are required.
command Required. Specifies the command that you want to carry out on each file, directory, range of values, or text string included in the specified (set).
CommandLineOptions Specifies any command-line options that you want to use with the specified command. /? Displays help at the command prompt.

Remarks
* Using for - You can use the for command within a batch file or directly from the command prompt.
* Using batch parameters
The following attributes apply to the for command:
= The for command replaces %variable or %%variable with each text string in the specified set until the command processes all of the files.
o For variable names are case-sensitive, global, and no more than 52 total can be active at any one time.
o To avoid confusion with the batch parameters %0 through %9, you can use any character for variable
except the numerals 0 through 9. For simple batch files, a single character such as %%f works. o You can use multiple values for variable in complex batch files to distinguish different replaceable variables.
* Specifying a group of files

The set parameter can represent a single group of files or several groups of files. You can use wildcards (that is, * and ?) to specify a file set. The following are valid file sets: (*.doc) (*.doc *.txt *.me) (jan*.doc jan*.rpt feb*.doc feb*.rpt) (ar??1991.* ap??1991.*)

When you use the for command, the first value in set replaces %variable or %%variable, and then the specified command processes this value. This continues until all of the files (or groups of files) that correspond to the set value are processed.

* Using the in and do keywords
In and do are not parameters, but you must use them with for. If you omit either of these keywords, an error message appears.

* Using additional forms of for
If command extensions are enabled (that is, the default), the following additional forms of for are supported:
o Directories only
If set contains wildcards (* and ?), the specified command executes for each directory (instead of a set of files in a specified directory) that matches set. The syntax is:
for /D {%% | %}variable in (set) do command [CommandLineOptions]

o Recursive
Walks the directory tree rooted at [Drive:]Path, executing the for statement in each directory of the tree. If no directory is specified after /R, the current directory is assumed. If set is just a single period (.), it only enumerates the directory tree. The syntax is:
for /R [[Drive :]Path] {%% | %}variable in (set) do command [CommandLineOptions]

o Iterating a range of values
Use an iterative variable to set the starting value (start#) and then step through a set range of values until the value exceeds the set ending value (end#). /L will execute the iterative by comparing start# with end#. If start# is less than end# the command will execute. When the iterative variable exceeds end# the command shell exists the loop. You can also use a negative step# to step through a range in decreasing values. For example, (1,1,5) generates the sequence 1 2 3 4 5 and (5,-1,1) generates the sequence (5 4 3 2 1). The syntax is:
for /L {%% | %}variable in (start#,step#,end#) do command [CommandLineOptions]

o Iterating and file parsing
Use file parsing to process command output, strings and file content. Use iterative variables to define the content or strings you want to examine and use the various ParsingKeywords options to further modify the parsing. Use the ParsingKeywords token option to specify which tokens should be passed as iterator variables. Note that when used without the token option, /F will only examine the first token.
File parsing consists of reading the output, string or file content, breaking it up into individual lines of text and then parsing each line into zero or more tokens. The for loop is then called with the iterator variable value set to the token. By default, /F passes the first blank separated token from each line of each file. Blank lines are skipped. The different syntaxes are:
for /F ["ParsingKeywords"] {%% | %}variable in (filenameset) do command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}variable in ("LiteralString") do command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}variable in ('command') do command [CommandLineOptions]

Example using multiple Keywords
@for /F "tokens=1,*skip=1delims=," %%i in (%TMPFIL%) do @(call :CHKME %%i)

The filenameset argument specifies one or more file names. Each file is opened, read and processed before going on to the next file in filenameset. To override the default parsing behavior, specify "ParsingKeywords". This is a quoted string that contains one or more keywords to specify different parsing options.

If you use the usebackq option, use one of the following syntaxes:
for /F ["usebackqParsingKeywords"] {%% | %}variable in ("filenameset") do command [CommandLineOptions]
for /F ["usebackqParsingKeywords"] {%% | %}variable in ('LiteralString') do command [CommandLineOptions]
for /F ["usebackqParsingKeywords"] {%% | %}variable in (`command`) do command [CommandLineOptions]

The following table lists the parsing keywords that you can use for ParsingKeywords.

Keyword Description
eol=c Specifies an end of line character (just one character).
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. As a result, additional variable names are 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 (*), an additional variable is allocated and receives the remaining text on the line after the last token that is parsed.
usebackq Specifies that you can use quotation marks to quote file names in filenameset, a back quoted string is executed as a command, and a single quoted string is a literal string command.

o Variable substitution - Substitution modifiers for for variable references have been enhanced. The following table lists optional syntax (for any variable I).

Variable with modifier
%~I Expands %I which removes any surrounding quotation marks ("").
%~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 Expands path to contain short names only.
%~aI Expands %I to the file attributes of file.
%~tI Expands %I to the date and time of file.
%~zI Expands %I to the 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, this modifier expands to the empty string.
The following table lists modifier combinations that you can use to get compound results.
Variable with combined modifiers
%~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.
%~ftzaI Expands %I to an output line that is like dir.
%~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.

In the above examples, you can replace %I and PATH by other valid values. A valid for variable name terminates the %~ syntax. By use uppercase variable names such as %I, you can make your code more readable and avoid confusion with the modifiers, which are not case-sensitive.

* Parsing a string
You can use the for /F parsing logic on an immediate string, by wrapping the filenameset between the parentheses in single quotation marks (that is, 'filenameset'). Filenameset is treated as a single line of input from a file, and then it is parsed.

* Parsing output
You can use the for /F command to parse the output of a command by making the filenameset between the parenthesis a back quoted string. It is 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 were a file.

Examples
To use for in a batch file, use the following syntax:
for %%variable in (set) do command [CommandLineOptions]
To display the contents of all the files in the current directory that have the extension .doc or .txt using the replaceable variable %f, type: for %f in (*.doc *.txt) do type %f

In the preceding example, each file that has the .doc or .txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.

To parse a file, ignoring commented lines, type:
for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens. If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

%i is explicitly declared in the FOR statement, and %j and %k are implicitly declared by using tokens=. You can specify up to 26 tokens using tokens=, provided that it does not cause an attempt to declare a variable higher than the letter 'z' or 'Z'.

To parse the output of a command by placing filenameset between the parentheses, type:
for /F "usebackq delims==" %i IN (`set`) DO @echo %i

This example enumerates the environment variable names in the current environment.

Output from '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.

EOF

index top

checked by Tidy   Valid HTML 4.01 Transitional

Wed, Sep 21, 2016 - Monday, July 22, 2013.