Windows 7 / Getting Started

Scanning for Files with the for Command

You often need to perform some command repeatedly with each of several files. CMD provides a command named for that helps save typing; it repeats a command for each item in a specified list.

At its simplest, for runs a command for every item placed in its set (a list of items in parentheses). For example,

for %x in (a b c) do echo %x

prints out three lines:

a
b
c

The set consists of the strings a, b, and c. For creates a temporary variable named x and issues the command echo %x three times, with x taking on the values a, b, and c in turn. In the command, any occurrence of %x is replaced by the value of x, so this for command is the equivalent of issuing these three commands:

echo a
echo b
echo c

(By the way, the choice of which letter to use for the variable is completely arbitrary. I picked x, but you can use any of the lowercase letters a to z or the uppercase letters A to Z. Oddly enough, case matters here.)

If any of the items in the set contain the wildcard characters * or ?, CMD replaces the items with the list of all matching filenames.Therefore, the command

for %x in (*.doc) do echo %x

runs the echo command once for each .doc file.

Note One tricky thing about for is that the percent sign (%) is considered a special character in batch files. When you use a for command in a batch file, you have to double up all the % signs used with the for variable. The previous for statement would have to be written this way in a batch file:

for %%x in (*.doc) do echo %%x

If you write lots of batch files, you get used to this, but then you have to remember to use only one % sign if you type a for command directly at the command prompt.

I show you how to exploit the for command in batch files in the next tutorial.

The for command in CMD is much more powerful than its COMMAND.COM equivalent. Several modifiers can be placed between the word for and the set to make for perform several useful tricks.

[Previous] [Contents] [Next]