很简单,我猜...我需要通过在下面的循环索引变量(%% i)中添加前导零来获得可用变量。
@echo off
for /L %%i in (1, 1, 5) do (
echo %%i
rem How to create a variable j here as a
rem result of adding leading zeros to %%i? (001, 002, 003 etc.)
)
pause
如何? 我已经尝试过以下内容,但是我无法从%% i变量中获取值,并且在var ...处...
@echo off & setlocal enableextensions
for /L %%i in (1, 1, 5) do (
echo %%i
set var_=00000%%i
set var_=%var_:~-5%
echo %var_%
)
pause
答案 0 :(得分:42)
使用零前缀字符串,然后从右侧获取所需的字符数:
@echo off
set count=5
setlocal EnableDelayedExpansion
for /L %%i in (1, 1, %count%) do (
set "formattedValue=000000%%i"
echo !formattedValue:~-3!
)
输出:
001
002
003
004
005
答案 1 :(得分:7)
使用setlocal enabledelayedexpansion
,解决方法就是:
@echo off
setlocal ENABLEDELAYEDEXPANSION
set count=5
for /L %%i in (1, 1, %count%) do (
echo %%i
set j=00%%i
rem to display intermediate values inside loop, surround with !
echo !j!
)
endlocal
这是一个很好的参考:http://blog.crankybit.com/why-that-batch-for-loop-isnt-working/