for - Loop Command

Maintained on

When writing batch files, you often encounter situations where you want to “run the same operation on multiple files” or “repeat a process a fixed number of times.”

The FOR command is what makes this kind of looping possible.

This article explains the FOR command from the basics through each option, with practical sample code.

Basic Syntax of the FOR Command

The basic syntax of the FOR command is as follows.

FOR %%variable IN (set) DO command
ElementDescription
%%variableA variable that receives each value in the loop (one letter, a–z or A–Z)
(set)The values, wildcards, or file set to iterate over
commandThe command to execute on each iteration
チェック

When running directly in Command Prompt, use %variable (one percent sign). Inside a batch file, use %%variable (two percent signs).

Basic Example

Here is a simple example that processes multiple values in sequence.

@echo off
setlocal

FOR %%i IN (apple orange grape) DO (
    echo %%i was selected
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>sample.cmd
apple was selected
orange was selected
grape was selected
C:\users\user>

Each value in the set is stored in %%i one at a time, and the command after DO is executed.

Iterating Over Files

Using wildcards, you can iterate over files that match a condition.

@echo off
setlocal

FOR %%f IN (*.txt) DO (
    echo File: %%f
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>list_txt.cmd
File: document.txt
File: memo.txt
File: readme.txt
C:\users\user>
おすすめ書籍※ 広告を含む場合があります
中小企業経営者のためのRPA入門 RPA導入を成功させる方法

中小企業経営者のためのRPA入門 RPA導入を成功させる方法

60分でわかる! AIエージェント 超入門

60分でわかる! AIエージェント 超入門

コマンドラインの黒い画面が怖いんです。

コマンドラインの黒い画面が怖いんです。

知識・才能ゼロでもらく~に月10万円稼ぐ! よくわかるAI副業超入門

知識・才能ゼロでもらく~に月10万円稼ぐ! よくわかるAI副業超入門

All .txt files in the current directory will be processed.

/L Option: Loop Over a Numeric Range

The /L option lets you loop while incrementing a number.

FOR /L %%variable IN (start, step, end) DO command
ParameterDescription
startThe starting value
stepThe amount added each iteration
endThe ending value

Count from 1 to 5

@echo off
setlocal

FOR /L %%n IN (1, 1, 5) DO (
    echo Count: %%n
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>count.cmd
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
C:\users\user>

Countdown in Steps of 2

A negative step value produces a countdown.

@echo off
setlocal

FOR /L %%n IN (10, -2, 0) DO (
    echo %%n
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>countdown.cmd
10
8
6
4
2
0
C:\users\user>

/D Option: Iterate Over Directories

The /D option iterates over directories only, not files.

FOR /D %%variable IN (pattern) DO command

Example

@echo off
setlocal

echo Folders in the current directory:
FOR /D %%d IN (*) DO (
    echo   [DIR] %%d
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>list_dirs.cmd
Folders in the current directory:
[DIR] Documents
[DIR] Downloads
[DIR] Pictures
C:\users\user>

/R Option: Recursive Loop Including Subdirectories

The /R option iterates through all subdirectories under a given root.

FOR /R [root path] %%variable IN (pattern) DO command

If the root path is omitted, the current directory is used.

Example: Search All .txt Files

@echo off
setlocal

echo Searching for all .txt files...
FOR /R %%f IN (*.txt) DO (
    echo Found: %%f
)

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>find_all_txt.cmd
Searching for all .txt files…
Found: C:\Users\user\Documents\readme.txt
Found: C:\Users\user\Documents\memo\note.txt
Found: C:\Users\user\Documents\backup\old.txt
C:\users\user>
チェック

Using the /R option in a directory with many files may take a long time.

/F Option: Read File Contents or Command Output

The /F option is the most powerful. It reads each line of a text file or processes the output of a command.

FOR /F ["options"] %%variable IN (input) DO command

Process Each Line of a Text File

@echo off
setlocal

echo Displaying file contents line by line:
FOR /F %%line IN (data.txt) DO (
    echo %%line
)

endlocal

Available Sub-options

OptionDescription
delims=charsDelimiter characters (default: space and tab)
tokens=nWhich token(s) to extract
skip=nNumber of lines to skip at the start
eol=charTreat lines starting with this character as comments
usebackqTreat backtick as command, single-quote as string, double-quote for paths with spaces

Example: Process a CSV File

@echo off
setlocal

echo Processing name,age,city CSV:
FOR /F "tokens=1,2,3 delims=," %%a IN (users.csv) DO (
    echo Name: %%a / Age: %%b / City: %%c
)

endlocal

With users.csv containing:

Alice,25,New York
Bob,30,Los Angeles
Charlie,28,Chicago
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>read_csv.cmd
Processing name,age,city CSV:
Name: Alice / Age: 25 / City: New York
Name: Bob / Age: 30 / City: Los Angeles
Name: Charlie / Age: 28 / City: Chicago
C:\users\user>

Process Command Output

Wrap a command in backticks to iterate over its output.

@echo off
setlocal

echo Counting files in the current directory:
set count=0
FOR /F %%f IN ('dir /b /a-d') DO (
    set /a count+=1
)
echo File count: %count%

endlocal
- □ ×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2026 Ribbit App Development All rights reserved.
 
C:\users\user>process_output.cmd
Counting files in the current directory:
File count: 5
C:\users\user>

Variable Modifiers

FOR variables support modifiers to extract file information.

ModifierDescription
%%~fFull path
%%~dDrive letter only
%%~pPath without drive
%%~nFilename without extension
%%~xExtension only
%%~zFile size in bytes
%%~tFile timestamp

Example

@echo off
setlocal

FOR %%f IN (*.txt) DO (
    echo File: %%f
    echo   Full path: %%~ff
    echo   Name: %%~nf
    echo   Extension: %%~xf
    echo   Size: %%~zf bytes
    echo.
)

endlocal

Practical Examples

Bulk Rename Files

@echo off
setlocal enabledelayedexpansion

set prefix=backup_
set count=1

FOR %%f IN (*.txt) DO (
    set newname=%prefix%!count!%%~xf
    echo Renaming %%f to !newname!
    ren "%%f" "!newname!"
    set /a count+=1
)

echo Done.
endlocal

Delete Old Log Files

@echo off
setlocal

echo Deleting log files older than 7 days...
FOR /F "delims=" %%f IN ('forfiles /p "C:\logs" /s /m *.log /d -7 /c "cmd /c echo @path" 2^>nul') DO (
    echo Deleting: %%f
    del "%%f"
)

echo Done.
endlocal

Summary

The FOR command is a powerful tool for looping in batch files.

Key points:

  • Basic syntax: FOR %%variable IN (set) DO command
  • /L option: Loop over a numeric range (start, step, end)
  • /D option: Iterate over directories only
  • /R option: Recursive loop including subdirectories
  • /F option: Read file contents or process command output

Practice Quiz

Quiz 1

Which is the correct FOR statement to display 1, 2, 3 in sequence inside a batch file?

回答がサーバーに送信されることはありません
Quiz 2

Which option is used to loop over a numeric range?

回答がサーバーに送信されることはありません
Quiz 3

Which is the correct syntax to count from 1 to 10 with the /L option?

回答がサーバーに送信されることはありません
In preparation
The linked page is currently under construction. Please wait a moment.
#Command Prompt #Batch File #FOR #Loop #Command