1

I have a text file which is made up of a new value on each line. The amount of lines will vary (expand over time).

I would like to set a variable in a batch file for each of those values. Does anybody know how to do that?

Andriy M
  • 76,112
  • 17
  • 94
  • 154
LabRat
  • 1,996
  • 11
  • 56
  • 91

1 Answers1

3

If you just want to read from each line of the file into separate variable then use this. It can also be configured into a loop if you want it to get all the lines instead of just specific lines that way you wouldn't have to put 100 commands for 100 lines.

setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (TEXTFILEPATH.txt) do (
set /a N+=1
set v[!N!]=%%a
)
set line1=%v[1]%
set line2=%v[2]%
set line3=%v[3]%
set line4=%v[4]%

echo %line1%
echo %line2%
echo %line3%
echo %line4%

endlocal

Make sure the endlocal is after the use of the variables.

If you want to write to specific lines in the text file, here is a post for that.

Write batch variable into specific line in a text file

Community
  • 1
  • 1
Spencer May
  • 4,266
  • 9
  • 28
  • 48
  • 1
    I suggest you to use the array notation for these variables: `set v[!N!]=%%a`, it is a clearer and standard form that everybody recognizes: http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini Nov 16 '12 at 19:58
  • I guess using the array notation would be easier to understand. I've never used it before until now I've always used the above code. I updated my code. – Spencer May Nov 18 '12 at 00:26