Batch Script - Create Dynamic Variable Names or Array in For Loop

£可爱£侵袭症+ 提交于 2019-12-24 00:16:45

问题


I would like to ask you if you can advise.

I don't know if it is possible to create dynamic variable names in batch or array or something like this. For example set c=0 before for loop and then set c = c+1 inside for loop and use this number to create dynamic variable name inside for loop e.g.: set entry%c% = 'somestring'

and afterwards use these numbered variables to print output outside for loop e.g.: echo %entry1% echo %entry2%

Example:

@echo off

set /a c=1

for %%i in (list.txt) do (

set /a c=c+1
set entry%c% = %%i

)

echo %entry1%
echo %entry2%

Thanks for help.


回答1:


I'd use

for /f "tokens=1*delims=[]" %%a in ('find /n /v "" list.txt') do set "entry%%a=%%b"

but a word of warning about

set entry%c% = %%i

Batch is sensitive to spaces in a SET statement. Had this worked, it would set a variable named "entry1Space" to a value of "Spacethefirstlineofthefile".

The set "var=value" syntax I've used ensures that any trailing spaces on the batch line are not included in the value assigned to var.




回答2:


You need to use delayed expansion variables, otherwise c will always expand to the same value.

You also need to remove the spaces in your set statement. set entry%c% = %%i will create a variable called (for example) entry1<space>, which you would have to expand like so - %entry1 %. So just remove those spaces around the = operator.

@echo off

setLocal enableDelayedExpansion
set c=0

for %%i in (list.txt) do (
    set /a c+=1
    set entry!c!=%%i
)

echo %entry1%
echo %entry2%

Also if you wanted to loop through all the variables you created, you could do something like the following.

for /L %%i in (!c!, -1, 1) do echo !entry%%i!

or

for /L %%i in (1, 1, !c!) do echo !entry%%i!


来源:https://stackoverflow.com/questions/24234994/batch-script-create-dynamic-variable-names-or-array-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!