0

I am having a list of id number like the following:

123
4456
657
23
199

i would like to add padding zero to it so that it will end up with 5 digit with result like this:

00123
04456
00657
00023
00199

I have looked up online but couldn't really find a solution for .bat file. I have tried something like the following:

set num_max=5
set my_num=123

set "my_num=00000%my_num%"
set "mynum=!my_num:!~-%num_max%!"
echo %my_num%

but the reuslt becomes something like 00000123. I have a loop to read all the input value

for /f "tokens=1" %%a in (.\config.ini) do (
echo %%a
)
``` and the %%a is the value that I would like to add the padding zero to.
bjwaap
  • 1
  • 1
    You are so unbelievably close; you just need to remove that middle `!` from `!my_num:!~-%num_max%!` to make it `!my_num:~-%num_max%!` and echo `%mynum%` instead of `%my_num%`. I'm voting to close because these are both typos, but you made an excellent attempt. – SomethingDark Feb 09 '21 at 04:21
  • thanks for the reply, but its now outputting ```"!my_num:~-5!"``` I have changed the two lines to ```set mynum=!my_num:~-%num_max%!"``` and ```echo %mynum%``` @SomethingDark – bjwaap Feb 09 '21 at 04:59
  • 2
    Do you have `setlocal EnableDelayedExpansion` line at beginning? – Aacini Feb 09 '21 at 06:10

1 Answers1

-1

If you wanted to press ahead and learn some PowerShell, you could easily do it with the following in a batch-file. If you are on a supported Windows system, PowerShell is available.

set "num_max=5"
set "my_num=123"
FOR /F "delims=" %%A IN ('powershell -NoLogo -NoProfile -Command "'%my_num%'.PadLeft(%num_max%,'0')"') DO (SET "my_num=%%~A")
ECHO my_num is %my_num%

Of course, it would be easier if the script were written in PowerShell.

$num_max = 5
$my_num = 123
$my_left_padded_num = "{0:$('0' * $num_max)}" -f $my_num 
$my_left_padded_num
lit
  • 14,456
  • 10
  • 65
  • 119