FOR - Repeat a command
Purpose: Repeat a command for several values of a variable.
Format: FOR [/A:[[-]rhsda] /D /F ["options "] /H /L /R [path ]] %var
IN ([@]set | start, step, end ) [DO] command ...
options : Parsing options for a "file parsing" FOR.
path : The starting directory for a "recursive" FOR.
%var : The variable to be used in the command ("FOR
variable").
set : A set of values for the variable.
start : The starting increment for a "counted" FOR.
step : The increment value for a "counted" FOR.
end : The limit value for a "counted" FOR.
command : A command or group of commands to be executed for
each value of the variable.
/A: (Attribute select) /L (counted loop)
/F(ile parsing) /R(ecursive)
/H(ide dots)
File Selection
Supports extended wildcards, ranges, multiple file names, and include
lists. Ranges must appear immediately after the FOR keyword.
Usage
FOR begins by creating a set. It then executes a command for every
member of the set. The command can be an internal command, an alias, an
external command, or a batch file. The members of the set can be a list
of file names, text strings, a group of numeric values, or text read from
a list of files.
When the set is made up of text or several separate file names (not an
include list), the elements must be separated by spaces, tabs, commas, or
the switch character (normally a slash [/]).
FOR includes a large number of options, some of which duplicate functions
available in other CMD.EXE commands, and/or do not follow conventions you
may find in our other commands. Most of these extra options are included
for compatibility with Windows NT 4.0's CMD.EXE. However, we make them
available in CMD.EXE, 4DOS, and 4NT so that aliases and batch files which
use them can work under all three products.
The first three sections below (Working with Files, Working with Text,
and Retrieving Text from Files) describe the traditional FOR command and
the enhancements to it which are part of CMD.EXE. The sections on
Parsing Text from Files and Counted FOR Loops describe features added for
compatibility of our line of text mode products with Windows NT 4.0. The
section entitled Other Notes contains information you may need if you use
any aspect of the FOR command extensively.
Working with Files
Normally, the set is a list of files specified with wildcards. For
example, if you use this line in a batch file:
for %x in (*.txt) do list %x
then LIST will be executed once for each file in the current directory
with the extension .TXT. The FOR variable %x is set equal to each of the
file names in turn, then the LIST command is executed for each file.
(You could do the same thing more easily with a simple LIST *.TXT. We
used FOR here so you could get a feel for how it operates, using a simple
example. Many of the examples in this section are constructed in the
same way.)
The set can include multiple files or an include list, like this:
for %x in (d:\*.txt;*.doc;*.asc) do type %x
FOR supports wildcards and extended wildcards, as well as extended parent
directory names (e.g., ...\*.txt to process all of the .TXT files that
are contained in the directory 2 levels above the current directory).
When you use FOR on an HPFS drive, you must quote any file names within
the set which contain whitespace or special characters. The same
restriction applies to names returned in the FOR variable, if you pass
them to CMD.EXE internal commands, or other commands which require
quoting filenames with whitespace. FOR does not quote returned names
automatically, even if you included quotes in the set. See File Names
for additional details on file name quoting.
If the set includes filenames, the file list can be further refined by
using date, time, size and file exclusion ranges. The range or ranges
must be placed immediately after the word FOR. Ranges will be ignored if
no wildcards are used inside the parentheses. For example, this set is
made up of all of the .TXT files that were created or updated on October
4, 1997:
for /[d10-4-97,+0] %x in (*.txt) do ...
If the command is an internal command that supports ranges, an
independent range can also be used in the command itself.
You can also refine the list by limiting it with the /A: option to select
only files that have specific attributes.
By default, FOR works only with files in the current directory or a
specified directory. With the /R option, FOR will also search for files
in subdirectories. For example, to work with all of the .TXT files in
the current directory and its subdirectories:
for /r %x in (*.txt) do ...
If you specify a directory name immediately after /R, FOR will start in
that directory and then search each of its subdirectories. This example
works with all of the .BAK files on drive D:
for /r d:\ %x in (*.bak) do ...
When you use wildcards to specify the set, FOR scans the directory and
finds each file which matches the wildcard name(s) you specified. If,
during the processing of the FOR command, you create a file that could be
included in the set, it may or may not appear in a future iteration of
the same FOR command. Whether the new file appears depends on its
physical location in the directory structure. For example, if you use
FOR to execute a command for all .TXT files, and the command also creates
one or more new .TXT files, those new files may or may not be processed
during the current FOR command, depending on where they are placed in the
physical structure of the directory. This is an operating system
constraint over which CMD.EXE have no control. Therefore, in order to
achieve consistent results you should construct FOR commands which do not
create files that could become part of the set for the current command.
Working with Text
The set can also be made up of text instead of file names. For example,
to create three files named file1, file2, and file3, each containing a
blank line:
for %suffix in (1 2 3) do echo. > file%suffix
You could also use the names of environment variables as the text. This
example displays the name and content of several variables from the
environment (see Environment Variables and Functions for details on the
use of square brackets when expanding environment variables). Enter this
on one line:
for %var in (path prompt comspec) do echo %var=%[%var]
Retrieving Text from Files
FOR can extract text from files in two different ways. The first method
extracts each line from each file in the set and places it in the
variable. To use this method, place an [@] at the beginning of the set,
in front of the file name or names.
For example, if you have a file called DRIVES.TXT that contains a list of
drives on your computer, one drive name per line (with a ":" after each
drive letter), you can print the free space on each drive this way:
for %d in (@drives.txt) do free %d > prn
Because the [@] is also a valid filename character, FOR first checks to
see if the file exists with the [@] in its name (i.e., a file named
@DRIVES.TXT ). If so, the filename is treated as a normal argument. If
it doesn't exist, FOR uses the filename (without the [@]) as the file
from which to retrieve text.
If you use @CON as the filename, FOR will read from standard input (a
redirected input file) or a pipe; see Redirection and Piping for more
information). If you use @CLIP: as the filename, FOR will read any text
available from the OS/2 clipboard (see Redirection for details).
Parsing Text from Files
The second method of working with text from files is to have FOR parse
each line of each file for you. To begin a "file-parsing" FOR, you must
use the /F option and then include one or more file names in the set.
When you use this form of FOR, the variable must be a single letter, for
example, %a.
This method of parsing, included for compatibility with Windows NT 4.0's
CMD.EXE, can be cumbersome and inflexible. For a more powerful method,
use FOR with @filename as the set to retrieve each line from the file, as
described in the previous section. Then use variable functions like
@INSTR, @LEFT, @RIGHT, and @WORD to parse the line.
By default, FOR will extract the first word or token from each line and
return it in the variable. For example, to display the first word on
each line in the file FLIST.TXT:
for /f %a in (flist.txt) do echo %a
You can control the way FOR /F parses each line by specifying one or more
parsing options in a quoted string immediately after the /F. The
available options are:
skip=n: FOR /F will skip "n" lines at the beginning of each file
before parsing the remainder of the file.
tokens=n, m, ... :
Bydefault ,FOR/ Freturnsjustthefirstwordor" token
"fromeachparsedlineinthevariableyounamed . You
canhaveitreturnmorethanonetokeninthevariable
,orreturntokensinseveralvariables ,withthisoption .
This option is followed by a list of numbers separated by
commas. The first number tells FOR /F which token to return
in the first variable, the second number tells it which to
return in the second variable, etc. The variables follow
each other alphabetically starting with the variable you
name on the FOR command line. This example returns the
first word of each line in each text file in %d, the second
in %e, and the third in %f:
for /f "tokens=1,2,3" %d in (*.txt) do ...
You can also indicate a range of tokens by separating the
numbers with a hyphen [-]. This example returns the first
word of each line in %p, the second through fifth words in
%q, and the eighth word in %r:
for /f "tokens=1,2-5,8" %p in (*.txt) do ...
To return the rest of the line in a variable, use a range
that ends with a number higher than the last token in any
line, such as 999. This final example returns the first
word of each line in %a and the remainder of each line
(assuming that no line has more than 999 words!) in %b:
for /f "tokens=1,2-999" %a in (*.txt) do ...
eol=c : If FOR /F finds the character "c" in the line, it will
assume that the character and any text following it are part
of a comment and ignore the rest of the line.
delims=xxx... :
Bydefault ,FOR/ Fseesspacesandtabsaswordortokendelimiters . This
option
replaces
those
delimiters
with
allofthecharactersfollowingtheequalsigntotheendofthestring . This
optionmustthereforebethelastoneusedinthequotedoptionsstring
.
You can also use FOR /F to parse a single string instead of each line of
a file by using the string, in quotes, as the set. For example, this
command will assign variable A to the string "this", B to "is", etc.,
then display "this" (enter the command on one line):
for /f "tokens=1,2,3,4" %a in ("this is a test") do echo %a
"Counted" FOR Loop
The "counted FOR" loop is included only for compatibility with Windows NT
4.0's CMD.EXE. In most cases, you will find the DO command more useful
for performing counted loops.
In a counted FOR command, the set is made up of numeric values instead of
text or file names. To begin a counted FOR command, you must use the /L
option and then include three values, separated by commas, in the set.
These are the start, step, and end values. During the first iteration
of the FOR loop, the variable is set equal to the start value. Before
each iteration, the variable is increased by the step value. The loop
ends when the variable exceeds the end value. This example will print
the numbers from 1 to 10:
for /l %val in (1,1,10) do echo %val
This example will print the odd numbers from 1 to 10 (1, 3, 5, 7, and 9):
for /l %val in (1,2,10) do echo %val
The step value can be negative. If it is, the loop will end when the
variable is less than the end value.
Other Notes
You can use either % or %% in front of the variable name. Either form
will work, whether the FOR command is typed from the command line or is
part of an alias or batch file (some of the traditional command
processors require a single % if FOR is used at the command line, but
require %% if FOR is used in a batch file). The variable name can be up
to 80 characters long. The word DO is optional.
If you use a single-character FOR variable name, that name is given
priority over any environment variable which starts with the same letter,
in order to maintain compatibility with the traditional FOR command. For
example, the following command tries to add a: and b: to the end of the
PATH, but will not work as intended:
[c:\] for %p in (a: b:) do path %path;%p
The "%p" in "%path" will be interpreted as the FOR variable %p followed
by the text "ath", which is not what was intended. To get around this,
use a different letter or a longer name for the FOR variable, or use
square brackets around the variable name (see Environment).
The following example uses FOR with variable functions to delete the .BAK
files for which a corresponding .TXT file exists in the current directory
:
[c:\docs] for %file in (*.txt) do del %@name[%file].bak
The above command would not work properly on an HPFS drive, because the
returned FILE variable might contain whitespace. To correct this
problem, you would need two sets of quotes, one for DEL and one for
%@NAME:
[c:\docs] for %file in (*.txt) do del "%@name["%file"].bak"
You can use command grouping to execute multiple commands for each
element in the set. For example, the following command copies each .WKQ
file in the current directory to the D:\WKSAVE directory, then changes
the extension of each file in the current directory to .SAV. This should
be entered on one line:
[c:\text] for %file in (*.wkq) do (copy "%file" d:\wksave\ &
ren "%file" *.sav)
In a batch file you can use GOSUB to execute a subroutine for every
element in the set. Within the subroutine, the FOR variable can be used
just like any environment variable. This is a convenient way to execute
a complex sequence of commands for every element in the set without
CALLing another batch file.
One unusual use of FOR is to execute a collection of batch files or other
commands with the same parameter. For example, you might want to have
three batch files all operate on the same data file. The FOR command
could look like this:
[c:\] for %cmd in (filetest fileform fileprnt) do %cmd datafile
This line will expand to three separate commands:
filetest datafile
fileform datafile
fileprnt datafile
The variable that FOR uses (the %CMD in the example above) is created in
the environment and then erased when the FOR command is done. (For
compatibility with CMD.EXE, a single-character FOR variable is created in
a special way that does not overwrite an existing environment variable
with the same name.) When using a multi-character variable name you must
be careful not to use the name of one of your environment variables as a
FOR variable. For example, a command that begins
[c:\] for %path in ...
will write over your current path setting, then erase the path variable
completely when FOR is done.
FOR statements can be nested.
Options
/A:: (Attribute select) Select only those files that have the
specified attribute(s) set. /A: will be used only when
processing wildcard file names in the set. It will be ignored
for filenames without wildcards or other items in the set.
Preceding the attribute character with a hyphen [-] will
select files that do not have that attribute set. The colon
[:] after /A is required. The attributes are:
R Read-only
H Hidden
S System
D Subdirectory
A Archive
If no attributes are listed (e.g., FOR /A: ...), FOR will
process all files including hidden and system files. If
attributes are combined, all the specified attributes must
match for a file to be included. For example, /A:RHS will
include only those files with all three attributes set.
For example, to process only those files with the archive
attribute set:
for /a:a %f in (*.*) echo %f needs a backup!
/F: (File parsing) Return one or more words or tokens from each
line of each file in the set. The /F option can be followed
by one or more options in a quoted string which control how the
parsing is performed. See the details under Parsing Text From
Files, above.
/H: (Hide dots) Suppress the assignment of the "." and ".."
directories to the FOR variable.
/L: (counted loop) Interpret the three values in the set as the
start, step, and end values of a counted loop. See the
details under "Counted" FOR Loop, above.
/R: (Recursive) Look in the current directory and all of its
subdirectories for files in the set. If the /R is followed by
a directory name, look for files in that directory and all of
its subdirectories.
Created using Inf-PHP v.2 (c) 2003 Yuri Prokushev
Created using Inf-HTML v.0.9b (c) 1995 Peter Childs