Monday, November 22, 2010

BATCH FILE: how do I read 3 lines of a text file into variables?

I know that I need to use the ';for'; keyword. All of the sites I found previously were confusing. Say on the desktop (it will not be on the desktop, but for simplicity's sake...) I have a file called CONFIG.txt and it contains three lines:

12

15

no

How do I get a batch file (also on the desktop for simplicity's sake) to read the values into environment variables? For example, VAR0 would contain ';12'; (no quotes), VAR1 would contain ';15';, and VAR2 would contain ';no';? Later in the program, I will do the following (the :: prefixes are not in the batch, but are used to clarify the start of each line thanks to Yahoo! Answers' funky wordwrap, in addition, the // is used to denote a comment as in C, although THIS IS A BATCH, NOT C):

::SET /A VN0=%VAR0% //sets VN0 to the val of the 1st line in CONFIG.txt

::SET /A VN1=%VAR1% //sets VN1 to the val of the 2nd line in CONFIG.txt

::SET /A VN1+=%VN0% //increases VN1 by VN0

::SET /A VNT=%RANDOM% %% %VN1% //RND# from (0)~(VN1-1)

::IF %VNT% LEQ %VN0% ECHO %VAR2%// is RND# less/eq to VN0?

in other words, my batch file should take a random number between 0 and 1 less than the sum of the first 2 lines of a text file, and then compare the random value to the first line again. if the random value is less than or equal to the value in the first line of CONFIG.txt, then it will ECHO what is in the third line.

Thanks for your help, I'm making a BATCH to change your Wallpaper, Screensaver, et cetera at each logon, but with many functions and options. If I can finish the BATCH (as in if I can figure out this speedbump) then I will put my stable version 4.0.0.0 for public download, as well as any updates I make. Thank you for your time in answering my question. My email address is emailmeatthisaddr@yahoo.com if you are interested in the BATCH or if you have any SUGGESTIONS FOR FEATURES, please email me. David A. De La Garza ~0xD5BATCH FILE: how do I read 3 lines of a text file into variables?
Hi,



Not sure about reading different lines into variables, but if you replace line breaks with ';;'; (ie your file looked like ';12;15;no';) then the following will work:



set var0=

set var1=

set var2=

for /f ';tokens=1,2,3 delims=;'; %%a in (CONFIG.txt) do (set var0=%%a %26amp; set var1=%%b %26amp; set var2=%%c)

No comments:

Post a Comment