在Windows批处理文件字符串处理:如何使用前导零填充值? [英] String processing in windows batch files: How to pad value with leading zeros?
问题描述
在Windows CMD批处理文件(.bat),我如何垫nuleric值,使得在范围0..99定值获得转化以在00至99的范围内的字符串。即我想有前导零值低于10。
in a Windows cmd batch file (.bat), how do i pad a nuleric value, so that given value in the range 0..99 get transformed to a string in the range "00" to "99". I.e. I'd like to having leading zeros for values lower than 10.
推荐答案
有一个两阶段的过程中,你可以使用:
There's a two-stage process you can use:
REM initial setup
SET X=5
REM pad with your desired width - 1 leading zeroes
SET PADDED=0%X%
REM slice off any zeroes you don't need -- BEWARE, this can truncate the value
REM the 2 at the end is the number of desired digits
SET PADDED=%PADDED:~-2%
现在 TEMP
持有的填充值。如果有任何机会的初始值 X
可能有超过2位数,你需要检查你不小心截断它:
Now TEMP
holds the padded value. If there's any chance that the initial value of X
might have more than 2 digits, you need to check that you didn't accidentally truncate it:
REM did we truncate the value by mistake? if so, undo the damage
SET /A VERIFY=1%X% - 1%PADDED%
IF NOT "%VERIFY%"=="0" SET PADDED=%X%
REM finally update the value of X
SET X=%PADDED%
重要提示:
此解决方案创建或覆盖变量 PADDED
和验证
。任何脚本,设置的这些并不意味着要坚持变量的值就终止应在 SETLOCAL
和 ENDLOCAL
语句prevent这些变化来自外界是可见的。
This solution creates or overwrites the variables PADDED
and VERIFY
. Any script that sets the values of variables which are not meant to be persisted after it terminates should be put inside SETLOCAL
and ENDLOCAL
statements to prevent these changes from being visible from the outside world.
这篇关于在Windows批处理文件字符串处理:如何使用前导零填充值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!