简体   繁体   中英

How can I get string from text file to an array in batch files?

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
@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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM