Monday 14 July 2008

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

So, let's see how we can loop through information.
The following script is the same as the previous but I have added a loop construct which will loop through our file_content variable (the first line of the file).

@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
set /P file_content=<file1.txt
for %%l in (%file_content%) do (
echo Content: %%l
)
goto eof

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

:blackhole

The loop construct is simple: for %%varname in (%var%) do ( ..[action]..)
The parentheses around the %var% are not in there just for form, you really need to remember them or your batch will crash.

To test it try using a file that contains a first line with spaces in it (e.g. The quick brown fox jumps over the lazy dog) and you will see that each word of the first line of the file will appear on a line of its own.

Excellent, the next step will be to loop through all the lines in a file.

Thoughts in the meantime?

No comments:

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