1

I have a file named file.txt that contains these numbers:

1 2 3 4 5

I need a batch file that takes the numbers from file.txt and saves them in an array. In the end the array should look like this:

a[0]=1 a[1]=2 a[2]=3...

Thank you!

Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
  • 1
    There are no real arrays in batch files, so I tend to call them pseudo-arrays. Anyway, there are array-like concepts. Check out this post to learn more: [Arrays, linked lists and other data structures in cmd.exe (batch) script](https://stackoverflow.com/a/10167990) – aschipfl Apr 17 '18 at 18:32

3 Answers3

1

Here is an alternative solution without need of delayed expansion:

@echo off
rem // Read first line of file:
< "file.txt" set /P LINE=""
rem // Initialise index number:
set /A "IDX=0"
rem // Loop through items/numbers from read line:
for %%J in (%LINE%) do (
    rem // Assign current array element:
    call set "A[%%IDX%%]=%%J"
    rem // Increment index number:
    set /A "IDX+=1"
)
rem // Return result:
set A[

The call command avoids delayed expansion by introducing a second parsing phase in order to read the variable IDX that is written/changed in the same loop.

This relies on the fact that all the numbers appear in a single line in the file. Note that the line must not be longer than 1021 characters.


This is another one, also without delayed expansion:

@echo off
rem // Initialise index number:
set /A "IDX=0"
rem // Read one line of file:
for /F "usebackq delims=" %%L in ("file.txt") do (
    rem // Loop through items/numbers from read line:
    for %%K in (%%L) do (
        rem // Retrieve current index number:
        for /F "tokens=1-2" %%I in ('set /A IDX') do (
            rem // Assign current array element:
            set "A[%%I]=%%K"
        )
       rem // Increment index number:
        set /A "IDX+=1"
    )
)
rem // Return result:
set A[

The for /F loop around the set /A command avoids delayed expansion here. set /A executed in cmd context (rather than batch context) returns the (last) result. Since it is executed by for /F, cmd context applies. for /F just captures the output, which is the value of variable IDX.

This accepts even numbers spread over multiple lines. Note that each line must not exceed a length of about 8090 characters.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
1

One more option for you using the SET command with string substitution.

@echo off
setlocal EnableDelayedExpansion

set i=0
set /p a=<file.txt
set "a[!i!]=%a: =" & set /A i+=1 & set "a[!i!]=%"
set a[
Squashman
  • 13,649
  • 5
  • 27
  • 36
0

If the numbers are on the same line :

You can make something like this :

@echo off
setlocal enabledelayedexpansion
set /p $list=<Your_Text_file.txt
set $count=0

for %%a in (%$list%) do (
  set "$array[!$count!]=%%a"
  set /a $count+=1
  )

set $array
SachaDee
  • 9,245
  • 3
  • 23
  • 33