更改代码中的变量名称

时间:2016-03-19 20:04:19

标签: batch-file

我想在批处理文件中更改变量的名称,因为这样我就不必24次输出相同的代码。

我想要这样的东西但实际上有效:

set n=1
set t=1

:loop

set /p %n%%t% = this will be variable %n%%t%:

echo %%n%%t%%

set /a n+=1
set /a t+=1

goto loop

3 个答案:

答案 0 :(得分:1)

您可以使用数组。试试这个:

set arrayline[%n%][%t%] = this will be variable %n%%t%:

答案 1 :(得分:1)

考虑使用FOR /L代替goto - 它会更快地运行,代码也会更加可行。尽管你还需要delayed expansion

@echo off
setlocal enableDelayedExpansion
set n=1
set t=1


for /l %%# in (1;1;24) do (

    set /p element[!n!][!t!]= enter the value of element[!n!!t!] : 
    set /a n+=1
    set /a t+=1
)
(echo()
echo listing elements:
(echo()
set element

endlocal

请注意,如果在分配变量值时在=左右留出空格,则空格将成为变量名称的一部分。

答案 2 :(得分:1)

两个错误。

首先,您已在所设置的变量中包含空格,如前所述。

其次,您不能将echo用于以数字开头的变量名。

您可以使用set 1(例如)查看变量,因此可以使用for /f "tokens-1*delims==" %%a in ('set 1') do if "%%a"=="1" echo %%b

之类的内容 例如,

提取环境变量1

的值

但是 - 简单地使用不以数字开头的变量名就容易多了。

%n其中n为0..9指的是相关例程的参数n。

相关问题