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

WindowsBatch File

Windows Problem Overview


I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.

Windows Solutions


Solution 1 - Windows

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

Solution 2 - Windows

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"

Solution 3 - Windows

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.

Solution 4 - Windows

Improving the first "FOR /F.." answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:

for /F "tokens=*" %A in  (MyList.txt) do CALL %A ARG1

--OR, if you wish to do it over the multiple line:

for /F "tokens=*" %A in  (MuList.txt) do (
ECHO Processing %A....
CALL %A ARG1
)

Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:

---START of MyScript.bat---
@echo off
for /F "tokens=*" %%A in  ( MyList.TXT) do  (
   ECHO Processing %%A.... 
   CALL %%A ARG1 
)
@echo on
;---END of MyScript.bat---

Solution 5 - Windows

@MrKraus's answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %~dp0. Here is an example:

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

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\Program Files'), use:

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

, with the type keyword calling the type program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.

I hope this helps someone!

Solution 6 - Windows

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

To read lines of any content, you need the delayed expansion toggling technic.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!" removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.

Solution 7 - Windows

Or, you may exclude the options in quotes:

FOR /F %%i IN (myfile.txt) DO ECHO %%i

Solution 8 - Windows

Here's a bat file I wrote to execute all SQL scripts in a folder:

REM ******************************************************************
REM Runs all *.sql scripts sorted by filename in the current folder.
REM To use integrated auth change -U <user> -P <password> to -E
REM ******************************************************************

dir /B /O:n *.sql > RunSqlScripts.tmp
for /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A
del RunSqlScripts.tmp

Solution 9 - Windows

If you have an NT-family Windows (one with cmd.exe as the shell), try the FOR /F command.

Solution 10 - Windows

The accepted anwser using cmd.exe and

for /F "tokens=*" %F in (file.txt) do whatever "%F" ...

works only for "normal" files. It fails miserably with huge files.

For big files, you may need to use Powershell and something like this:

[IO.File]::ReadLines("file.txt") | ForEach-Object { whatever "$_" }

or if you have enough memory:

foreach($line in [System.IO.File]::ReadLines("file.txt")) { whatever "$line" } 

This worked for me with a 250 MB file containing over 2 million lines, where the for /F ... command got stuck after a few thousand lines.

For the differences between foreach and ForEach-Object, see Getting to Know ForEach and ForEach-Object.

(credits: Read file line by line in PowerShell )

Solution 11 - Windows

Modded examples here to list our Rails apps on Heroku - thanks!

cmd /C "heroku list > heroku_apps.txt"
find /v "=" heroku_apps.txt | find /v ".TXT" | findstr /r /v /c:"^$" > heroku_apps_list.txt
for /F "tokens=1" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i

Full code here.

Solution 12 - Windows

To print all lines in text file from command line (with delayedExpansion):

set input="path/to/file.txt"

for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!)

Works with leading whitespace, blank lines, whitespace lines.

Tested on Win 10 CMD

Test text

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr. KrausView Question on Stackoverflow
Solution 1 - WindowsMr. KrausView Answer on Stackoverflow
Solution 2 - WindowsAshView Answer on Stackoverflow
Solution 3 - Windowsuser332474View Answer on Stackoverflow
Solution 4 - WindowsYogesh MahajanView Answer on Stackoverflow
Solution 5 - WindowsMarvin ThobejaneView Answer on Stackoverflow
Solution 6 - WindowsjebView Answer on Stackoverflow
Solution 7 - WindowsPaulView Answer on Stackoverflow
Solution 8 - WindowsmikejView Answer on Stackoverflow
Solution 9 - WindowsMichael RatanapinthaView Answer on Stackoverflow
Solution 10 - WindowsmivkView Answer on Stackoverflow
Solution 11 - WindowsDotDotJamesView Answer on Stackoverflow
Solution 12 - WindowsZimbaView Answer on Stackoverflow