Home > Commands A-M > Batch F

FOR


Description | Syntax | Parameters | Switches | Related | Notes | Examples | Errorlevels | Availability

Runs a specified command for each file in a set of files. You can use this command in batch programs or at the command prompt.


Syntax

FOR /?

To use FOR in a batch program:

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

To use FOR from the command prompt:

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


Parameters
command (v2.0 Win95 NT3.5)
Specifies the command that you want to carry out on each file included in the specified set.
command-parameters (v2.0 Win95 NT3.5)
Specifies any parameters or switches that you want to use with the specified command (if the specified command uses any parameters or switches).
(set) (v2.0 Win95 NT3.5)
Specifies one or more files or text strings that you want to process with the specified command. The parentheses are required.
%variable or %%variable (v2.0 Win95 NT3.5)
Represents a replaceable variable. The FOR command replaces %%variable (or %variable) with each text string in the specified set until the command (specified in the command parameter) processes all the files. Use %%variable to carry out the FOR command within a batch program. Use %variable to carry out FOR from the command prompt. (Do NOT use %0 through %9 to avoid confusion with the command-line arguments passed to the batch file).
Variable names are case sensitive, so %i is different from %I.

Switches
/? (NTXP)
Display help.

Related

See LFNFOR to use FOR with long filenames.
FOR /R - Loop through files (recurse subfolders).
FOR /D - Loop through several folders.
FOR /L - Loop through a range of numbers.
FOR /F - Loop through items in a text file.
FOR /F - Loop through the output of a command.
FORFILES - Batch process multiple files.
GOTO - Direct a batch program to jump to a labelled line.
IF - Conditionally perform a command.
Equivalent Linux BASH commands:
cut - Divide a file into several columns.
for - Expand words, and execute commands.
eval - Evaluate several COMMANDS/arguments.
if - Conditionally perform a command.
m4 - Macro processor.
until - Execute commands (until error).
while - Execute commands.


Notes
Escaping embedded spaces in folder names

When a source folder has space(s), they need to be escaped with ^. NT3.5

ie. to copy a single file:

    FOR %%G IN (c:\program^ files\MyFile.txt) DO copy %%G d:\backups\

Nested FOR commands

FOR commands can be nested FOR %%G... DO (FOR %%T... DO ...) when nesting commands choose a different letter for each part. you can then refer to both parameters in the final DO command. (NT4)


Using the IN and DO keywords

IN and DO are not parameters, but they are required in the FOR command. If you omit either of these keywords, the operating system displays an error message.


Using the replaceable variable

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 programs, a single character such as %%f may be all that is necessary.

You can use multiple values for variable in complex batch programs to distinguish different replaceable variables. However, you can only nest (add multiple FOR commands on the same command-line) with NT4

In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value.

If this results in a single value then %%G is set = to that value and the command is performed.

If this results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...

For example:

    FOR /F %%G IN ("This is a long sentence") DO @echo %%G %%H %%J

will result in the output:

    This is long

You can of course pick any letter of the alphabet other than %%G.

%%G is a good choice because it does not conflict with any of the pathname format letters (d,f,n,p,s,x) and provides the longest run of alphabetic letters for use as implicit parameters. G > H > I > J > K > L > M

The second best choice is %%T: T > U > V > W

Environment variables within a FOR loop are expanded at the beginning of the loop. So the snippet will not produce the expected result:

    SET count=1 FOR /F "tokens=*" %%G IN ('dir /b') DO (
echo %count%:%%G
set /a count+=1)

To force the variable to get evaluated at the proper iteration, use the new subroutine CALL mechanism to take the evaluation outside of the loop:

    SET count=1 FOR /F "tokens=*" %%G IN ('dir /b') DO (
call :exec
set /a count+=1
echo %%count%%:%%a)
    GOTO :eof

    :exec
    %*
    GOTO :eof

    :eof

Specifying a group of files

The set parameter can represent a single group of files or several groups of files. You can use wildcards (* and ?) to specify a file set. The 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 the operating system carries out the specified command in order to process this value; this continues until the operating system has processed all the files (or groups of files) that correspond to the value (or values) in set.


Using the slash character

UNDOCUMENTED Beginning with v3.30 you can read ONLY the first set character, by using slash (/):

    FOR %f IN (/ABCD) DO echo %f

This will result in:

    A
    BCD

Using (enhanced) variable references

Exhancement of FOR variable names, beginning with NT2000 have been changed:

    %~          - expands removing any surrounding quotes ("), ie. %~I
    %~a         - expands to file attributes, ie. %~aI
    %~d         - expands to a drive letter only, ie. %~dI
    %~f         - expands to a fully qualified path name, ie. %~fI
    %~n         - expands to a file name only, ie. %~nI
    %~p         - expands to a path only, ie. %~pI
    %~s         - expanded path contains short names only, ie. %~sI
    %~t         - expands to date/time of file, ie. %~tI
    %~x         - expands to a file extension only, ie. %~xI
    %~z         - expands to size of file, ie. %~zI
    %~$PATH:    - expands to full qualified name of first file found
                   by searching the %PATH% directories, ie. %~$PATH:I
                  OR expands to the empty string
                    (environment variable not defined or file not found)

Combinations are allowed:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension 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

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.


Examples

Suppose you want to use the TYPE command to display the contents of all the files in the current directory that have the extension .DOC or .TXT. To do this and to use the replaceable variable %f, type:

    FOR %f IN (*.doc *.txt) DO TYPE %f

In this 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, you would replace every occurrence of %f with %%f. Otherwise, the operating system ignores the variable and displays an error message.

The operating system supports command switches, pipes, and redirection that you may want to use with the specified command. For example, to redirect the output of the previous example to PRN (the default printer port), you would type:

    FOR %f IN (*.doc *.txt) DO TYPE %f > PRN:

Errorlevels

none.


Availability
Internal
DOS
v2.0 v2.01 v2.05 v2.10 v2.11 v2.11R v2.12 v2.2 v2.25 v3.0 v3.20 v3.05 v3.1 v3.21 v3.25 v3.30 v3.3A v3.3R v3.3T v3.31 v3.40 v4.0 v4.01 v4.01A v5.0 v5.0A v5.00.02 v5.001A v5.01 v5.02 v6.0 v6.10 v6.2 v6.21 v6.22 v6.23 v7.00 v7.0R1 v7.10 v8.00
Windows
Win95 Win98 WinME
Windows NT
NT3.5 NT4 NT2000 NTXP NT2003