Batchography: Reading a text file line by line in Batch files

This is yet another article about Batch files. In this article, I am going to show you how to read a text file line by line using the Batch files scripting language.

For more advanced Batch scripting topics, please grab a copy of the Batchography book.

batchography-good-res

Let’s get started!

flower separator

In Batch files, to open and read files, you have to use the FOR /F switch which is usually used to tokenize the input it receives.

Here’s the specific FOR /F syntax needed to read the Batch files line by line:

@echo off
for /f "delims=" %%a in (the-file.txt) DO ( 
  ECHO Line is: %%a
)

Replace the variable name “a” and the input text file “the-file.txt” with your file and variable name.

Let’s see the contents of the-file.txt:

Line 1
Line 2

Line 4
Line 5, ...

Note how line 3 is left intentionally blank. Now let’s run the script and observe the output:

C:\Batchography>read-line-by-line.bat
Line is: Line 1
Line is: Line 2
Line is: Line 4
Line is: Line 5, ...

C:\Batchography>

Did you notice something missing? Yes, line 3 is not displayed and that’s because empty lines are skipped by design.

That’s it for this article but not everything regarding the powerful FOR /F switch and its tokenizing capabilities, stay tuned!flower separatorYou might also like:

Leave a Reply