String processing in windows batch files: How to pad value with leading zeros?

前端 未结 7 654
时光取名叫无心
时光取名叫无心 2020-11-27 19:07

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

7条回答
  •  余生分开走
    2020-11-27 19:36

    @echo off
    rem .
    rem   counter example - with and without padding (up to 260 leading 0s which should be enough for most filenames)
    rem .
    rem   we assume values given are valid
    rem   additional error checking could be done to make sure they are numbers
    rem   and to ensure that starting is less than ending
    rem   and that the number of ending digits is not greater than the number of padding digits
    rem .
    if "%2"=="" (
      echo.
      echo usage:   %~nx0 [starting number] [ending number] [pad]
      echo example: %~nx0  0  19        will output numbers 0 to 19 each on a new line
      echo example: %~nx0  3  12  8     will output numbers 3 to 12 each on a new line padded to 8 digits
      echo.
      goto end
      )
    rem .
    setlocal enabledelayedexpansion
    if "%3"=="" (
      for /l %%x in (%1, 1, %2) do (
        echo.%%x
      )
    ) else (
      set "mynum="
      for /l %%x in (%1, 1, %2) do (
        call set "mynum=00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000%%x"
        call set "mynum=%%mynum:~-%3%%"
        call echo.%%mynum%%
      )
    )
    :end
    

提交回复
热议问题