Scr*_*tch 24 windows batch-file
在Windows cmd批处理文件(.bat)中,如何填充数值,以便0..99范围内的给定值转换为"00"到"99"范围内的字符串.即我希望值低于10的前导零.
Jon*_*Jon 25
您可以使用两个阶段的流程:
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%
Run Code Online (Sandbox Code Playgroud)
现在TEMP保持填充值.如果初始值X可能超过2位,则需要检查您是否意外截断它:
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%
Run Code Online (Sandbox Code Playgroud)
重要的提示:
此解决方案创建或覆盖变量PADDED和VERIFY.任何设置变量值的脚本都应放在内部SETLOCAL和ENDLOCAL语句中,以防止这些变量从外部世界可见.
dbe*_*ham 16
如果您确信原始数字中的位数始终<= 2,那么
set "x=0%x%"
set "x=%x:~-2%"
Run Code Online (Sandbox Code Playgroud)
如果数字可能超过2位数,并且您想要填充2位数,但不截断大于99的值,那么
setlocal enableDelayedExpansion
if "%x%" equ "%x:~-2%" (
set "x=0%x%"
set "x=!x:~-2!"
)
Run Code Online (Sandbox Code Playgroud)
或者没有延迟扩展,使用中间变量
set paddedX=0%x%
if "%x%" equ "%x:~-2%" set "x=%paddedX:~-2%"
Run Code Online (Sandbox Code Playgroud)
关于上述算法的好处是将填充扩展到任意宽度是微不足道的.例如,要填充到宽度10,只需添加9个零并保留最后10个字符
set "x=000000000%x%"
set "x=%x:~-10%"
Run Code Online (Sandbox Code Playgroud)
防止截断
set paddedX=000000000%x%
if "%x%" equ "%x:~-10%" set "x=%paddedX:~-10%"
Run Code Online (Sandbox Code Playgroud)
单行
IF 1%Foo% LSS 100 SET Foo=0%Foo%
Run Code Online (Sandbox Code Playgroud)
将为您提供您指定范围内的数字所需的内容.如果它们已经是单填充的,则它不会更改子集0-9中的值.
Previous answers had explained all the existent methods to pad a value with left zeros; I just want to add a small trick I used to do that in an easier way. What had not been enough mentioned in previous answers is that in most cases, the value that will be padded is incremented inside a loop and that the padded value is just used to display it (or similar tasks, like renames). For example, to show values from 00 to 99:
set x=0
:loop
rem Pad x value, store it in padded
set padded=0%x%
set padded=%padded:~-2%
rem Show padded value
echo %padded%
set /A x+=1
if %x% leq 99 goto loop
Run Code Online (Sandbox Code Playgroud)
If this is the case, the value of the variable may be used for both control the loop and display its padded value with no modification if its limits are appropriately translated. For example, to show values from 00 to 99:
set x=100
:loop
rem Show padded value
echo %x:~-2%
set /A x+=1
if %x% leq 199 goto loop
Run Code Online (Sandbox Code Playgroud)
This method works also with any number of left zeros to pad.
Antonio
| 归档时间: |
|
| 查看次数: |
34346 次 |
| 最近记录: |