Windows 7 / Getting Started

Using the For Command

The For command fulfills a special niche in batch file programming. You can use wildcard characters to make multiple file selections when needed. Unfortunately, using wildcard characters won't always work. Sometimes you need to know the name of the file. A command line utility might not support wildcard characters or the file argument doesn't easily fit within the wildcard method of description. That's where the For statement comes into play for batch files. This command takes the form:

FOR %%variable IN (set) DO command [command-parameters]

You can also use this command at the command prompt to process files manually. Instead of using a single percent (%) symbol, you use two in front of the variable. Here's a sample of how you can use this command in a batch file.

Echo Off
For %%F In (*.BAT *.TXT) Do Dir %%F /B
Echo On

In this case, the For command processes all of the files that have a BAT or TXT extension in the current directory. The command processes the files in the order in which they appear in the directory and you have no guarantee what the order is. The %%F variable contains the name of an individual file. The Dir command is called once for each file with the %%F variable as an input. In this case, the command outputs the filenames using the bare format, so you could use this batch file to create a text file containing a list of files that match the criteria. Additional processing could archive the files or do anything else that you might like. The For command provides the following arguments.

{%Variable | %%Variable} Specifies a replaceable parameter; the argument that will receive the individual members of a set. The replaceable parameter takes two forms. Use the %Variable form when you want to use the replaceable parameter as input to another command or utility. Use the %%Variable form when you want to use the replaceable parameter for activities within the batch file. The variable names are case sensitive, so %f isn't the same as %F. In addition, you must use an alphabetical variable name, such as %A, %B, or %C.

(Set) Defines the set to process. The set can include one or more files, directories, range of values, or text strings that you want to process with the specified command. For example, you can use environment variables as the set. The command For %%P In (%PATH%) Do ECHO %%P would display the members of the PATH environment variable as individual strings.

Command Specifies the command you want to perform for each entry in the set.

CommandLineOptions Defines the command line options for the command that you want to perform for each entry in the set. The command line options are command or utility specific.

Performing Complex File Iteration

You can use the For command to process command output, strings, and the content of files. In this case, the For command begins by breaking the input into individual lines of content and discarding any blank lines. It then breaks whatever input you provide into specific tokens based on the rules you specify. A token can be a control character, a special word, or anything else you can define as part of the simple syntax for this command. The For command passes the token to a command you specify as input. Here's the command line syntax for this form of the For command.

for /F ["ParsingKeywords"] {%% | %}Variabe lin (FileNameSet) do Command
    [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}Variable in ("LiteralString") do
    Command [CommandLineOptions]
for /F ["ParsingKeywords"] {%% | %}Variable in ('Command') do Command
    [CommandLineOptions]

Notice that you need to use a different command line syntax for each kind of input. A filename appears without quotes, while a string appears in double quotes and a command appears in single quotes. The small differences in command format determines how the For command views the input.

The ParsingKeywords input is a quoted string that specifies the rules for parsing the input into tokens. These keywords always appear in double quotes, as shown. The following list describes the keywords you can use.

eol=c Specifies an end of line character. The For command only allows you to specify one character.

skip=N Specifies the number of lines to skip at the beginning of the file.

delims=xxx Specifies a delimiter set. The delimiter set defines which characters the For command views as elements between tokens. The default setting relies on the space and tab. Consequently, the For command produces a new token every time it sees a space or tab within the input.

tokens=X,Y,M-N Defines which tokens to retrieve from each line of text to pass to the For command body for each iteration. The For command allocates one variable for each of the tokens. The M-N format defines a range of tokens to use as input. Whenever the last character in a processed string is an asterisk (*), the For command creates an additional variable to receive the additional text on the line after the For command parses the last token.

usebackq Specifies that you can use quotation marks to quote filenames in FileNameSet, a back quoted string is executed as a command, and a single quoted string is a literal string command.

You need to use a slightly different command line syntax with the For command when you rely on the usebackq keyword. Here are the three command lines using this syntax.

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]

Using Variable Substitution

Variable substitution is the act of exchanging a variable name for the content of that variable. However, unlike expansion, you don't necessarily use all of the variable content. For example, instead of using the entire path for a file, you might just use the drive letter, the path, or the filename. The following list describes the basic forms of variable substitution available with the For command. (The list assumes that you're using a variable named I, which translates into %I at the command line.)

%~I Removes any surrounding quotation marks from the variable content.
%~fI Expands %I to a fully qualified pathname.
%~dI Expands %I to a drive letter only.
%~pI Expands %I to a path only.
%~nI Expands %I to a filename only.
%~xI Expands %I to a file extension only.
%~sI Creates a path variable, and then changes any long directory names into their short name equivalents.
%~aI Obtains the file attributes of the input file.
%~tI Obtains the date and time of the input file.
%~zI Obtains the size of the input file.
%~$PATH:I Searches the directories listed in the PATH environment variable for the file specified by I. The system then expands the first match that it finds to a fully qualified filename, which includes the drive, path, and filename. This variable substitution returns an empty string when the PATH environment variable is undefined or if the system can't find a match for the filename.

You can use these variable substitutions in combination to produce specific results. For example, you might want to create a directory-like listing of files. The following list provides some ideas on how to use the variable substitution arguments in combination.

%~dpI Outputs just the drive letter and path of a file, without including the filename.
%~nxI Outputs the filename and extension, but leaves out the drive letter and path.
%~fsI Outputs the file information using the short name (8.3 format) form only.
%~dp$PATH:I Locates the file using the PATH environment variable. The system outputs just the drive letter and path of the first match found.
%~ftzaI Creates the same output as the Dir command. However, the output is different from the Dir command because the file listing could span multiple directories. The focus of the listing is different.
[Previous] [Contents] [Next]