windows Win bat 文件:如何在 for 循环中为变量添加前导零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9430642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:16:16  来源:igfitidea点击:

Win bat file: How to add leading zeros to a variable in a for loop?

windowsloopsbatch-file

提问by Cambiata

Very simple, I guess... I need to get a usable variable by adding leading zeros to the loop index variable (%%i) below.

很简单,我猜...我需要通过向下面的循环索引变量 (%%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

How? I've tried the following, but I can't get the value out of the %%i variable inte the var_ at a...

如何?我已经尝试了以下方法,但我无法从 %%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

回答by jeb

Prefix the string with zeros and then take the desired count of characters from the right side:

用零前缀字符串,然后从右侧获取所需的字符数:

@echo off
set count=5
setlocal EnableDelayedExpansion

for /L %%i in (1, 1, %count%) do (
     set "formattedValue=000000%%i"
     echo !formattedValue:~-3!
)

Outputs:

输出:

001
002
003
004
005

回答by vaisakh

Using the setlocal enabledelayedexpansion, the solution is this:

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

Here is a good reference: http://blog.crankybit.com/why-that-batch-for-loop-isnt-working/

这是一个很好的参考:http: //blog.crankybit.com/why-that-batch-for-loop-isnt-working/