首页 > 解决方案 > 如何制作将数组内容保存到文件的批处理文件循环

问题描述

我需要一段 Windows 批处理代码,它打印从数组的索引 0 开始的任意长度的内容到文件,每个值都转到文件中的新行。

这是我尝试使用的代码:

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

所以我希望它创建一个examplefile.txt包含数组内容的文件!array%i%!,例如,如果数组的内容是 exampledata1and exampledata2,则文件应该包含

exampledata1
exampledata2

但是在执行过程中,它只是第一次跳过循环, if not defined !array%i%! goto endsaveloop 即使!array%i%!在那个时候已经明确定义了。

标签: arraysbatch-file

解决方案


你可能会发现

set array>examplefile

或者

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

有用。

set array显示所有以 start 开头的变量名的当前(即运行时)值array

第一个的格式应该是

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

因此您可以轻松地重新加载数组

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

第二个应该只是屈服

37
61
89
55

请注意,这是严格按变量名的字母顺序排列的。

至于你的问题,你需要变量的if not defined array%i%内容而没有变量本身。例如,如果变量名的内容是.!array%i%!!if (not) defined 4array%i%4


推荐阅读