user11748497
user11748497

Reputation:

How to make a batch-file loop that saves the content of an array to a file

I'm in need of a piece of Windows batch code that prints the contents of an arbitrary length starting from index 0 from array to a file with each value going to a new line in the file.

This is the code i tried to use for it:

setlocal EnableDelayedExpansion
set i=0
:saveloop
if not defined !array%i%! goto endsaveloop
echo !array%i%! >> examplefile.txt
set/a i+=1
goto saveloop
:endsaveloop

So I expect it to create file called examplefile.txt consisting of the content of the array !array%i%!, for example if the content of the array was exampledata1 and exampledata2, the file should contain

exampledata1
exampledata2

but during execution it just jumps the first time through the loop at if not defined !array%i%! goto endsaveloop even though !array%i%! is definitely defined at that point.

Upvotes: 0

Views: 57

Answers (2)

Ben Personick
Ben Personick

Reputation: 3264

I usuallly use Set to iterate through arrays as long as I pad with 0s if the sequence is important

Upvotes: 0

Magoo
Magoo

Reputation: 80023

You may find

set array>examplefile

or

for /f "tokens=1*delims==" %%a in ('set array 2^>nul') >>examplefile

useful.

set array displays the current (ie. runtime) values of all variablenames that start array.

The format of the first should be

array1=37
array10=61
array11=89
array2=55
...

so you can easily reload the array exactly as it was with

for /f "delims=" %%a in ('type examplefile') do set "%%a"

The second should just yield

37
61
89
55

Note that this is in strict alphabetical order of the variablenames.

As for your problem, you need if not defined array%i% as !array%i%! is the contents of the variable whereas without the ! it is the variable itself. You would for instance be executing if (not) defined 4 if the contents of the variablename array%i% was 4.

Upvotes: 1

Related Questions