How to do a for loop in windows command line?
Categories:
Mastering For Loops in Windows Command Line (CMD)

Learn how to effectively use for
loops in Windows Command Prompt for various tasks, from iterating files to processing command output.
The for
loop is a powerful command-line utility in Windows that allows you to automate repetitive tasks by iterating over a set of items. Whether you need to process files in a directory, parse text, or execute commands multiple times, understanding for
loops is essential for efficient scripting in the Windows environment. This article will guide you through the different syntaxes and common use cases of the for
command.
Basic For Loop Syntax
The for
command in Windows CMD has several variations, each designed for specific iteration scenarios. The most common syntax involves iterating over a set of files or directories. The basic structure includes a variable, a set of items to iterate over, and the command to execute for each item.
FOR %variable IN (set) DO command [command-parameters]
General syntax for the FOR
command in CMD.
Let's break down the components:
%variable
: A single letter (e.g.,%a
,%b
). When used in a batch file, you must use%%variable
(e.g.,%%a
).IN (set)
: Specifies the items to iterate over. This can be a list of files, directories, or strings.DO command
: The command to execute for each item in theset
.[command-parameters]
: Any additional parameters for the command.
%%variable
when writing for
loops within a .bat
or .cmd
script, and %variable
directly in the command prompt. This is a common source of errors for beginners.Iterating Through Files and Directories
One of the most frequent uses of the for
loop is to process files or directories. You can specify wildcards to match multiple items. The /R
switch allows for recursive iteration through subdirectories.
:: Iterate through all .txt files in the current directory
FOR %f IN (*.txt) DO ECHO %f
:: Iterate through all files in the current directory and its subdirectories
FOR /R . %f IN (*) DO ECHO %f
:: Iterate through all subdirectories in the current directory
FOR /D %d IN (*) DO ECHO %d
Examples of iterating through files and directories.
flowchart TD A["Start For Loop"] --> B{"Is it a file or directory iteration?"} B -->|File/Directory| C["Specify `IN (set)` with wildcards"] C --> D{"Recursive?"} D -->|Yes| E["Add `/R` switch"] D -->|No| F["Proceed"] E --> G["Execute `DO command` for each item"] F --> G G --> H["End For Loop"] B -->|Directory Only| I["Add `/D` switch"] I --> G
Flowchart for deciding FOR
loop switches for file/directory iteration.
Parsing Command Output with FOR /F
The FOR /F
command is incredibly versatile, allowing you to parse the output of commands, read lines from files, and tokenize strings. This is particularly useful for extracting specific pieces of information.
:: Read each line from a file
FOR /F "delims=" %i IN (myfile.txt) DO ECHO %i
:: Parse the output of the 'dir' command to get filenames
FOR /F "tokens=4*" %a IN ('dir /b') DO ECHO %a
:: Tokenize a string by spaces
FOR /F "tokens=1,2,3" %a IN ("This is a test string") DO (
ECHO Token 1: %a
ECHO Token 2: %b
ECHO Token 3: %c
)
Examples of using FOR /F
for parsing.
Key options for FOR /F
:
"delims=chars"
: Specifies a set of delimiters. By default, space and tab are delimiters."tokens=x,y,z"
: Specifies which tokens (parts of the string separated by delimiters) to extract.*
means all remaining tokens."skip=n"
: Skips the firstn
lines."eol=char"
: Specifies an end-of-line character (lines starting with this character are ignored).IN ('command')
: Executes a command and processes its output.IN ("string")
: Processes a literal string.IN (file)
: Reads and processes lines from a file.
FOR /F
with tokens
, remember that %a
is the first token, %b
the second, and so on. The variable letters are sequential. If you specify tokens=1,3
, the first token goes to %a
and the third to %b
.Looping with Numeric Ranges
The FOR /L
command allows you to iterate through a sequence of numbers, which is useful for tasks requiring a fixed number of iterations or when generating numerical data.
:: Loop from 1 to 5 with a step of 1
FOR /L %i IN (1,1,5) DO ECHO %i
:: Loop from 10 down to 0 with a step of -2
FOR /L %j IN (10,-2,0) DO ECHO %j
Examples of numeric FOR
loops.
The syntax for FOR /L
is FOR /L %variable IN (start,step,end) DO command
.
start
: The starting number.step
: The increment or decrement value.end
: The ending number.
1. Identify Your Iteration Need
Determine what you need to loop through: files, directories, command output, or a range of numbers.
2. Choose the Correct FOR
Switch
Use FOR
for basic file/directory iteration, FOR /R
for recursive, FOR /D
for directories only, FOR /F
for parsing, or FOR /L
for numeric ranges.
3. Define Your Variable and Set
Assign a single-letter variable (e.g., %i
) and specify the IN (set)
based on your chosen switch (e.g., (*.log)
, ('type file.txt')
, (1,1,10)
).
4. Specify the DO
Command
Write the command you want to execute for each item. Use the variable within the command (e.g., ECHO %i
, DEL %f
). For multiple commands, enclose them in parentheses ()
.
5. Test and Refine
Run your for
loop in a test environment. If using in a batch file, remember to change %variable
to %%variable
.