Windows 批处理文件中的字符串处理:如何用前导零填充值? [英] String processing in windows batch files: How to pad value with leading zeros?

查看:18
本文介绍了Windows 批处理文件中的字符串处理:如何用前导零填充值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows cmd 批处理文件 (.bat) 中,如何填充数值,以便将 0..99 范围内的给定值转换为00"到99"范围内的字符串.IE.对于小于 10 的值,我希望使用前导零.

in a Windows cmd batch file (.bat), how do i pad a numeric value, so that a given value in the range 0..99 gets 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%

重要提示:

此解决方案创建或覆盖变量 PADDEDVERIFY.任何设置在终止后不打算保留的变量值的脚本都应放在 SETLOCALENDLOCAL 语句中,以防止这些更改从外部可见世界.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆