Page 1 of 1

Strange behavior

Posted: 20 Dec 2011 14:42
by roy437
Hi,

This scprit put zeros in front of numbers. For counter=1 and counter=2, the result is wrong. Why? I run on Windows Vista 32 bits.

Script:

@echo off
:: zero leading (ex. 1 --> 001, 2 -->002, ...., 99 --> 099...)
if exist m.txt del m.txt
set "z=000"
set n=111
set counter=1
:loop
if %counter% leq %n% (
set "m=%z%%counter%"
set "v=%m:~-3%"
echo.%v% %counter% >> m.txt
set /a counter+=1
goto loop
)
pause

Script Output:

1
~-3 2
001 3
002 4
003 5
004 6
005 7
006 8
007 9
008 10
009 11
010 12
…………..

Thx

Re: Strange behavior

Posted: 20 Dec 2011 14:53
by Tesrym
I came across this problem when making something similar.
When performing an arithmetic operation with set /a, it removes "obese" zeros.
10+1 becomes 11, but 01+1 becomes 2.
Sadly, I didn't create a solution for this, but I will follow this thread with curiosity.

Re: Strange behavior

Posted: 20 Dec 2011 15:16
by !k
roy437
use setlocal enabledelayedexpansion and !variable!

Tesrym
read set/? about "0" and "0x" prefix

Re: Strange behavior

Posted: 20 Dec 2011 15:22
by orange_batch
Implementation of what !k said:

Code: Select all

@echo off
setlocal enabledelayedexpansion
:: zero leading (ex. 1 --> 001, 2 -->002, ...., 99 --> 099...)
if exist m.txt del m.txt
set "z=000"
set n=111
set counter=1
:loop
if %counter% leq %n% (
  set "m=%z%%counter%"
  set "v=!m:~-3!"
  echo.!v! %counter% >> m.txt
  set /a counter+=1
  goto loop
)
pause

Or...

Code: Select all

@echo off
:: zero leading (ex. 1 --> 001, 2 -->002, ...., 99 --> 099...)
if exist m.txt del m.txt
set "z=000"
set n=111
set counter=1
:loop
if %counter% leq %n% (
  set "m=%z%%counter%"
  call set "v=%%m:~-3%%"
  call echo.%%v%% %counter% >> m.txt
  set /a counter+=1
  goto loop
)
pause

And yet again we have to explain delayed expansion. :P

Tesrym wrote:I came across this problem when making something similar.
When performing an arithmetic operation with set /a, it removes "obese" zeros.
10+1 becomes 11, but 01+1 becomes 2.
Sadly, I didn't create a solution for this, but I will follow this thread with curiosity.

The requirement to pad zeroes is typically always to a specific digit. So...

Code: Select all

:: Make sure number is 8 digits long, padded with 0s.
set padded=0000000012345
set padded=%padded:~-8%
echo %padded%

Strip zeroes:

Code: Select all

for /f "delims=0 tokens=*" %%a in ("00000102030") do set stripped=%%a
echo %stripped%

Re: Strange behavior

Posted: 20 Dec 2011 16:13
by roy437
Many thanks to orange_batch and !k. You are great !