Batch Txt Loop with Delimiter

From scripting
Jump to: navigation, search

Looping through a txt file is a common and important task. This article explains the procedure to do so.


setLocal EnableDelayedExpansion
For /f "tokens=1,2,3,4,5 delims=§" %%a in (trap.txt) Do (
Echo.%%a %%b %%c %%d %%e

Delimiting is the boundary between strings in your txt file. This separates words and phrases. In common English syntax, Periods delimit sentences, spaces delimit words, and returns delimit paragraphs.

In order to loop through a text file (.txt), you will need to establish a delimitation character. You will want to use a character that is not very common or not used in other programming syntax. In this example, I use the § (section) character.

To set the delimit character, use the following syntax:


Tokens explain how many objects to extract. If you just want the first delimiting string...


If you want the first two strings...


If you want the first and third strings...


And so on. You are limited to 26 consecutive strings.

To establish the looping variable, use one of the standards:


Inside your loop, you can extract as many delimited strings as you have declared in the "tokens" portion of the code. So, if you wrote...


you'll be able to echo the following...

Echo.%%a %%b %%c %%d %%e

If you wrote %%f in addition to a thru e, it would appear blank, because your tokens only went up to 5.