Batch file tip: Reading & writing every line of a file

By: klint
October 23, 2008

Applies to: Windows Command Processor for Windows NT and later versions (including XP and Vista.)

The FOR /F command can read successive lines from a file. Type FOR /? for full help. However, it has certain traps that can catch you out. One of these is that it skips blank lines. To stop it doing this, filter the file through FIND /N /V "", which prints out each line preceded by "[line-number]". Then, get the FOR loop to print out each line skipping past the "]" that ends the line number:

@echo off
for /f "delims=] tokens=1*" %%a in ('find /v /n "" ^<%1') do (

Note that the redirection character < has to be escaped by a caret ^ as shown above. Also, note how the ECHO command has a "." after it. This prevents it from printing "Echo is off" when the line is blank.

This technique works with one caveat. Any lines beginning with one or more closing brackets ] will have these brackets removed.

You can type the above into a file, call it typefile.cmd, and then run it by giving it a file name as parameter:

typefile myfile.txt

Need more help?
Describe your Problem
Example: Hard Drive Not Detected on My PC

Ask Question