Strange behavior

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
roy437
Posts: 2
Joined: 20 Dec 2011 13:59

Strange behavior

#1 Post by roy437 » 20 Dec 2011 14:42

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

Tesrym
Posts: 2
Joined: 15 Dec 2011 23:20

Re: Strange behavior

#2 Post by Tesrym » 20 Dec 2011 14:53

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.

!k
Expert
Posts: 378
Joined: 17 Oct 2009 08:30
Location: Russia

Re: Strange behavior

#3 Post by !k » 20 Dec 2011 15:16

roy437
use setlocal enabledelayedexpansion and !variable!

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

orange_batch
Expert
Posts: 442
Joined: 01 Aug 2010 17:13
Location: Canadian Pacific
Contact:

Re: Strange behavior

#4 Post by orange_batch » 20 Dec 2011 15:22

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%

roy437
Posts: 2
Joined: 20 Dec 2011 13:59

Re: Strange behavior

#5 Post by roy437 » 20 Dec 2011 16:13

Many thanks to orange_batch and !k. You are great !

Post Reply