3

I have a text file like this

myFile.txt:

apple 
banana
grapes

I want to drag text file to batch file and set variables into an array like this:

array[0]=apple
array[1]=banana
array[2]=grapes

But i couldn't do that. My problem is not just printing them but i can't even do that. I'll do parse operations at the rest of batch file. My Code:

@echo off
setlocal EnableDelayedExpansion

set i=0
for /f %%a in %1 do (
set /a i+=1
set array[!i!]=!a!
)
echo %array[0]%
echo %array[1]%
echo %array[2]%
endlocal

1 Answers1

4
@echo off
setlocal EnableDelayedExpansion

set i=0
for /f "usebackq" %%a in ("%~1") do (
   set /a i+=1
   set array[!i!]=%%a
)
echo %array[1]%
echo %array[2]%
echo %array[3]%

rem Or:

for /L %%i in (1,1,%i%) do echo !array[%%i]!

endlocal
pause

I suggest you to read this answer.

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • 2
    @AlperTheCoder, "it doesn't work" is not a quite precise failure description, is it? – aschipfl Feb 24 '17 at 15:00
  • 1
    Ops! If the filename may contain spaces or special characters, the `for /f` requires `usebackq` switch, as @aschipfl indicated in a comment... – Aacini Feb 24 '17 at 15:05