所以当我运行这段代码时:
@echo off
setlocal enabledelayedexpansion
set lstFolders= First Second
set intCounter=0
for %%i in (!lstFolders!) do (
set /a intCounter += 1
set strFlder=%%i
set strFolder!intCounter!=!strFlder!
echo %%i
echo !strFlder!
echo !strFolder%intCounter%!
echo !strFolder1!
echo !strFolder2!
)
:End
pause
endlocal
结果如下:
First
First
ECHO is off.
First
ECHO is off.
Second
Second
ECHO is off.
First
Second
为什么它不允许我使用以下格式回显变量:!strFolder%intCounter%!
?是否有另一种方法来引用此变量并获取其中的数据?
答案 0 :(得分:1)
正如@ mklement0所说,你需要一个额外的评估步骤
但是,尽管使用echo "%%strFolder!intCounter!%%"
,我建议延迟扩展
由于延迟扩展不受任何内容的影响,echo "%%strFolder...
将失败,内容包含引号或感叹号。
@echo off
setlocal enabledelayedexpansion
set "lstFolders=First Second"
set intCounter=0
for %%i in (!lstFolders!) do (
set /a intCounter+= 1
set "strFlder=%%i"
set "strFolder!intCounter!=!strFlder!"
echo !strFlder!
set "varname=strFolder!intCounter!"
for /F "delims=" %%A in (""!varname!"") do echo Indirect %%~A=!%%~A!
)
引号的加倍避免了FOR / F循环的eol字符问题。
答案 1 :(得分:0)
警告:以下代码仅适用于列表值(%lstFolders%
的令牌,例如First
):
& | < > "
处理此类案件需要采用不同的循环方法。
@echo off
setlocal enabledelayedexpansion
set "lstFolders=First Second"
set intCounter=0
for %%i in (%lstFolders%) do (
rem Increment the counter
set /a intCounter += 1
rem Echo the loop variable
echo #!intCounter!=%%i
rem Set variable strFolder<intCounter> to the loop variable's value
set "strFolder!intCounter!=%%i"
rem Echo the variable created using variable indirection with for /f ('...')
for /f "delims=" %%v in ('echo "%%strFolder!intCounter!%%"') do set "thisFolder=%%~v"
echo %%thisFolder%% ^(via %%strFolder!intCounter!%%^)=!thisFolder!
)
运行上述产量:
#1=First
%thisFolder% (via %strFolder1%)=First
#2=Second
%thisFolder% (via %strFolder2%)=Second
您正在寻找的是变量间接:
set "strFolder!intCounter!=%%i"
,!intCounter!
的值为1
,将变量strFolder1
正确设置为%%i
),你不能获取 变量的价值;您需要额外评估步骤,for /f ... ('echo ...')
可以提供。:
for /f "delims=" %%v in ('echo "%%strFolder!intCounter!%%"') do ...
用单引号(echo ...
)解析命令的输出,并将结果作为整体(delims=
)分配给变量%%v
(%%~v
删除在echo
参数周围添加的封闭双引号,以使命令正确处理shell元字符,例如& | < >
。
%%strFolder!intCounter!%%
立即评估strFolder!intCounter!
至strFolder1
,如果!intCounter!
为1
,感谢封闭 doubled %
实例,最终为 literal %strFolder1%
,这是echo
命令在运行时所看到的内容for
命令,使其评估变量引用并扩展为其值。