Batch Txt Loop with Delimiter

From scripting
Revision as of 04:54, 22 April 2017 by Nickpisca (talk | contribs) (Created page with "Looping through a txt file is a common and important task. This article explains the procedure to do so. Example... setLocal EnableDelayedExpansion For /f "tokens=1,2,3,4...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

Example...

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:

delims=§

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

tokens=1

If you want the first two strings...

tokens=1,2

If you want the first and third strings...

tokens=1,3

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

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

%%a

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...

tokens=1,2,3,4,5

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.