Win bat文件:如何将前导零添加到for循环中的variables?

非常简单,我猜…我需要通过向下面的循环索引variables(%% i)添加前导零来获得可用的variables。

@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 

怎么样? 我已经尝试了以下,但我无法获取%%我variables的值var_ 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 

Solutions Collecting From Web of "Win bat文件:如何将前导零添加到for循环中的variables?"

在字符串前加零,然后从右侧取所需的字符数:

 @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 

使用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/