How to create an array from a txt file in a batch file?

I have a txt file with the data below

aaaa 1000 2000 bbb 3000 4000 cccc 5000 ddd 6000 7000 8000 

The number of lines in this file is not fixed.

I need the first token of each line in the array and print each element.

+3
source share
3 answers

To create an array:

 setlocal EnableDelayedExpansion set i=0 for /F %%a in (theFile.txt) do ( set /A i+=1 set array[!i!]=%%a ) set n=%i% 

To print array elements:

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

If you want to pass the array name and length as parameters of the subroutine, use the following method:

 call theSub array %n% :theSub arrayName arrayLen for /L %%i in (1,1,%2) do echo !%1[%%i]! exit /B 
+12
source

try the following:

 @echo off for /F "tokens=1,2*" %%x in (myFile.txt) do echo %%x 

double % is required for use in a batch file, but you can check it on the cmd line with a single % s.

in a nutshell, for will iterate over myFile.txt to split each line into two tokens using the default delimiter (space).

+2
source

try this and call it from anywhere

 @echo off for /f "usebackq" %%a in ('%2') do set d=%%~a for /f "usebackq tokens=* delims=%d%" %%G in ('%3') do set %1=%%~G set /ai=-1 for %%h in (!%1!) do ( set /a i+=1 set %1[!i!]=%%h ) 
0
source

Source: https://habr.com/ru/post/1492207/


All Articles