Set variable from line in text file

August 16, 2010 at 16:44:50
Specs: Windows XP
How would I be able to set the first line in a text file as variable1 and the second line as a variable2 then the third line in a text file as variable3?

Text File Example:
first line
second line
third line

Then when I echo variable1 it would say "first line". Thanks for your reply!

See More: Set variable from line in text file

Report •

August 16, 2010 at 20:20:31
Try this:

@echo off
setlocal enabledelayedexpansion
set nbr=1

for /f "tokens=*" %%1 in (filename.txt) do (
set var!nbr!=%%1
set /a nbr+=1
if !nbr! gtr 3 goto list

echo VAR1 = %var1%
echo VAR2 = %var2%
echo VAR3 = %var3%

Report •

August 17, 2010 at 08:27:48
it works I just made a little edit to the script here is my edit:

@echo off
setlocal enabledelayedexpansion
set linecount=1
for /f "tokens=1 delims=" %%a in (FILENAME.txt) do (
set line!linecount!=%%a
set /a linecount=!linecount!+1
echo %line1%
echo %line2%
echo %line3%

Report •

August 17, 2010 at 14:13:12
That's fine & thanks for coming back to share with us.

You will be aware that because there is no escape from the loop after processing the first three lines, if filename.txt contains more than three lines you are creating a variable for each line. No big deal tho'.


Report •

Related Solutions

August 17, 2010 at 15:54:29
Yea I know about that but for what I am using it for it wont matter if extra variables are made.

Report •

Ask Question