How do you loop through each line in a text file using a windows batch file?

In a Batch File you MUST use %% instead of % : (Type help for)

for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
set VAR1=%1
set VAR2=%2
set VAR3=%3
COMMANDS TO PROCESS INFORMATION
goto :EOF

What this does: The "do call :process %%i %%j %%k" at the end of the for command passes the information acquired in the for command from myfile.txt to the "process" 'subroutine'.

When you're using the for command in a batch program, you need to use double % signs for the variables.

The following lines pass those variables from the for command to the process 'sub routine' and allow you to process this information.

set VAR1=%1
 set VAR2=%2
 set VAR3=%3

I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.


I needed to process the entire line as a whole. Here is what I found to work.

for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.

For Command on TechNet


If there are spaces in your file path, you need to use usebackq. For example.

for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A

From the Windows command line reference:

To parse a file, ignoring commented lines, type:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

By the way, you can find the command-line help file on most Windows systems at:

 "C:\WINDOWS\Help\ntcmds.chm"