for /f: Parse Text
for /f is CMD's text processor. It reads text line by line, splits each line into tokens (fields), and runs a command with the fields in loop variables. It can read three kinds of sources:
for /f "options" %%a in (file.txt) do ... lines of a file
for /f "options" %%a in ("some text") do ... a literal string
for /f "options" %%a in ('command') do ... the output of a commandIt's how batch files read config files, parse CSV, and capture the output of a command into a variable.
Reading a file line by line
With no options, for /f splits each line at spaces and tabs and gives you only the first word. To get the whole line, set delims= to nothing:
@echo off
> todo.txt echo buy milk
>> todo.txt echo call the bank
>> todo.txt echo fix the bike
echo --- default (first token only):
for /f %%l in (todo.txt) do echo %%l
echo --- delims= (whole line):
for /f "delims=" %%l in (todo.txt) do echo %%l--- default (first token only):
buy
call
fix
--- delims= (whole line):
buy milk
call the bank
fix the bike
Two things are silently skipped: empty lines, and lines starting with the end-of-line character, which is ; by default (see eol below).
The options
| Option | Meaning |
|---|---|
delims=xyz |
the characters that separate tokens (default: space and tab); delims= means none |
tokens=2,4 |
which tokens to keep; they go into %%a, %%b, ... in order |
tokens=1-3 |
a range of tokens |
tokens=1,* |
* means "the rest of the line" as one last variable |
skip=n |
skip the first n lines (a header row) |
eol=c |
lines starting with c are comments and are ignored (default ;) |
usebackq |
changes quoting: "file name" is a file, `cmd` is a command, 'text' is a string |
Options go in one quoted string, separated by spaces: "skip=1 tokens=1,3 delims=,". If delims= appears, put it last, otherwise a space you meant as a separator between options becomes a delimiter.
Splitting fields: tokens and delims
The first token goes into the variable you name; the next tokens go into the following letters of the alphabet:
@echo off
> people.csv echo name,city,age
>> people.csv echo Ada,London,36
>> people.csv echo Linus,Helsinki,54
>> people.csv echo Grace,Arlington,85
for /f "skip=1 tokens=1,3 delims=," %%a in (people.csv) do echo %%a is %%b years oldAda is 36 years old
Linus is 54 years old
Grace is 85 years old
tokens=1,3 puts field 1 in %%a and field 3 in %%b. skip=1 drops the header line. Because the letters are allocated in order, use a variable early in the alphabet (%%a) when you ask for several tokens.
The rest of the line: *
tokens=1,* splits once: the first field, then everything else as it was. That's perfect for key=value files where the value itself may contain = or spaces:
@echo off
> app.cfg echo # settings for the demo
>> app.cfg echo name=Weekly report
>> app.cfg echo url=https://example.com/?a=1
>> app.cfg echo retries=3
for /f "eol=# tokens=1,* delims==" %%k in (app.cfg) do (
echo [%%k] = [%%l]
set "cfg_%%k=%%l"
)
echo The report is called "%cfg_name%".[name] = [Weekly report]
[url] = [https://example.com/?a=1]
[retries] = [3]
The report is called "Weekly report".
eol=# turns # lines into comments, delims== splits at =, and set "cfg_%%k=%%l" creates one variable per key.
Parsing a string
A quoted string in the parentheses is parsed like a one-line file. It's useful for splitting a value you already have:
@echo off
set "release=2025-03-17"
for /f "tokens=1-3 delims=-" %%a in ("%release%") do (
echo year=%%a month=%%b day=%%c
)
set "full=Ada Lovelace"
for /f "tokens=1,2" %%f in ("%full%") do echo first=%%f last=%%gyear=2025 month=03 day=17
first=Ada last=Lovelace
tokens=1-3 fills %%a, %%b and %%c. If you started at %%y, the third token would land in the character after z, so choose a starting letter that leaves room, as the second loop does with %%f and %%g.
Capturing command output
Single quotes run a command and loop over its output. This is how you store the output of a command in a variable, the batch equivalent of Bash's $(command):
@echo off
mkdir inbox
> inbox\a.txt echo 1
> inbox\b.txt echo 2
> inbox\c.txt echo 3
set /a count=0
for /f "delims=" %%n in ('dir /b /o:n inbox') do set /a count+=1
echo inbox contains %count% files
for /f "delims=" %%n in ('dir /b /o:n inbox ^| sort /r') do set "last=%%n"
echo after a reverse sort, the last line is %last%
for /f "delims=" %%h in ('hostname') do set "host=%%h"
echo this computer is %host%inbox contains 3 files
after a reverse sort, the last line is a.txt
this computer is TAD
The first loop runs once per output line, which makes it a line counter. Inside the single quotes, a pipe | must be escaped as ^| (and > as ^>, & as ^&), because CMD parses the for line before it runs the command. When the loop runs more than once, a set inside it keeps the last line, as the second loop shows.
usebackq: file names with spaces
Without usebackq, a double-quoted name means "a string", so you can't read a file whose name has spaces. usebackq swaps the meanings:
@echo off
> "my notes.txt" echo first note
>> "my notes.txt" echo second note
for /f "usebackq delims=" %%l in ("my notes.txt") do echo read: %%l
for /f "usebackq delims=" %%l in (`echo command output`) do echo ran: %%lread: first note
read: second note
ran: command output
Totals and counters
Combine for /f with set /a to aggregate data. set /a reads total itself when it runs, so no delayed expansion is needed for the sums:
@echo off
> sales.txt echo north 120
>> sales.txt echo south 75
>> sales.txt echo north 30
>> sales.txt echo east 200
set /a total=0, lines=0
for /f "tokens=1,2" %%r in (sales.txt) do (
set /a total+=%%s, lines+=1
if "%%r"=="north" set /a north+=%%s
)
echo %lines% lines, total %total%, north %north%4 lines, total 425, north 150
north was never initialised: set /a treats an undefined variable as 0. The echo is after the loop, so plain %total% works there; to print the running total inside the loop you would need !total! (see setlocal & Delayed Expansion).
Pitfalls
- Empty lines vanish and lines starting with
;are skipped. Usefindstr /n "^" fileto number lines first if you must keep blanks, or seteol=to a character that never appears. !disappears from the data when delayed expansion is on, because!starts a variable reference. Turn delayed expansion on only where needed.- Unicode files:
for /freads ANSI/UTF-8 text; a UTF-16 file (what PowerShell 5.1's>writes) comes out garbled.
Comparison with other shells
| Task | CMD | Bash | PowerShell |
|---|---|---|---|
| each line | for /f "delims=" %%l in (f) |
while read -r l; do ... done < f |
Get-Content f |
| split fields | "tokens=1,3 delims=," |
IFS=, read -r a b c / cut |
Import-Csv, -split |
| command output | for /f %%x in ('cmd') |
x=$(cmd) |
$x = cmd |
Learn more: Bash Loops, awk, PowerShell CSV & JSON, Batch for Loops.
Test yourself
Which options read the whole line into %%l?
- "tokens=1"
- "delims="
- "skip=0"
- no options
In for /f "tokens=2,4 delims=;" %%a in (data.txt), where does field 4 end up?
- %%a
- %%b
- %%d
- %%4
How do you store the output of hostname in a variable?
- set host=hostname
- set host=%hostname%
- for /f "delims=" %%h in ('hostname') do set "host=%%h"
- hostname > %host%