Tuesday 15 July 2008

Batch programming tip#08 (part 3): Reading from a file - Looping

This post will bring an end (I think) to this thread about file reading using batch.

To use the loop command on a file we simply add /F in our FOR loop construct like so:

@echo off

:init_vars
if exist file1.txt goto action
echo Oops. file1.txt doesn't exist. Please create it or change file name.
goto eof

:action
for /F %%l in (file1.txt) do (
echo Content: %%l
)
goto eof

:eof
echo Press any key to close window...
pause > nul
goto blackhole

:blackhole

This will probably work with most configuration files you might use. There is one additional parameter that's really useful though, especially if your lines contain spaces. The FOR loop will by default only return the first token up to a delimiter character. The default delimiter characters are space and tab. This means the script above will only return the first word of any line containing spaces.

To avoid this (usually unwanted) behaviour, use the delims parameter and set it to empty as in the following code:

@echo off

:init_vars
if exist file1.txt goto action
echo Oops. file1.txt doesn't exist. Please create it or change file name.
goto eof

:action
for /F "delims=" %%l in (file1.txt) do (
echo Content: %%l
)
goto eof

:eof
echo Press any key to close window...
pause > nul
goto blackhole

:blackhole


Notice how we have added to our for construct:
for /F "delims=" %%l in (file1.txt) do

You can set "delims=" to whatever you want in effect, you could for instance use comma instead: "delims=,".

Well, I think that's it, you can of course take file reading much further if you want. In that case, you might want to check Rob van der Woude's comprehensive page about NT FOR syntax. Enjoy!

More shortly about how to loop through directories.

Thoughts in the meantime?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory