for - Loop Command
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
| Element | Description |
|---|---|
%%variable | A 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 |
command | The 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
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

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

60分でわかる! 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
| Parameter | Description |
|---|---|
| start | The starting value |
| step | The amount added each iteration |
| end | The ending value |
Count from 1 to 5
@echo off
setlocal
FOR /L %%n IN (1, 1, 5) DO (
echo Count: %%n
)
endlocal
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
/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
/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
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
| Option | Description |
|---|---|
delims=chars | Delimiter characters (default: space and tab) |
tokens=n | Which token(s) to extract |
skip=n | Number of lines to skip at the start |
eol=char | Treat lines starting with this character as comments |
usebackq | Treat 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
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
Variable Modifiers
FOR variables support modifiers to extract file information.
| Modifier | Description |
|---|---|
%%~f | Full path |
%%~d | Drive letter only |
%%~p | Path without drive |
%%~n | Filename without extension |
%%~x | Extension only |
%%~z | File size in bytes |
%%~t | File 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 /Loption: Loop over a numeric range (start, step, end)/Doption: Iterate over directories only/Roption: Recursive loop including subdirectories/Foption: Read file contents or process command output