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
4
  • 4
    Surely you mean, set "array[!i!]=%%a". Commented Feb 24, 2017 at 14:11
  • 4
    Did not think the parentheses for the IN clause were optional with the FOR command. Commented Feb 24, 2017 at 14:13
  • 4
    You've also got an off-by-one issue since you increment i before using it. Commented Feb 24, 2017 at 14:23
  • Change the for line to for /F "usebackq delims=" %%a in ("%~1") do ( to avoid trouble with certain characters in path/file names... Commented Feb 24, 2017 at 14:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@AlperTheCoder, "it doesn't work" is not a quite precise failure description, is it?
Ops! If the filename may contain spaces or special characters, the for /f requires usebackq switch, as @aschipfl indicated in a comment...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.