This page is edited from the 1cmdfaq.txt faq-file contained in
my tscmd.zip
command line interface (CLI) collection. That zipped file has much
additional material, including a number of detached .cmd script
files. It is recommended that you also get the zipped version as a
companion.
Please see "
The Description and
the Index page" for the conditions of usage and other such
information.
119} How can I remove any leading zeros from an unsigned integer?
First try the following and you'll see why this can be important
@echo off & setlocal enableextensions
set s_=008
set /a s_=%s_%+2
endlocal & goto :EOF
The output will be
C:\_D\TEST>cmdfaq
Invalid number. Numeric constants are either decimal (17),
hexadecimal (0x11), or octal (021).
To remove the leading zeros (and leading spaces)
@echo off & setlocal enableextensions
set s_= 008
echo %s_%
echo %s_%|findstr [123456789]>nul
if %errorlevel% EQU 0 (
for /f "tokens=* delims=0 " %%a in ('echo %s_%') do (
set s_=%%a)
) else (set s_=0)
echo %s_%
endlocal & goto :EOF
The output will be
C:\_D\TEST>cmdfaq
008
8
or slightly simpler
@echo off & setlocal enableextensions
set s_= 0092010
echo %s_%
if %s_% EQU 0 set s_=0
for /f "tokens=* delims=0 " %%a in ('echo %s_%') do set s_=%%a
echo %s_%
endlocal & goto :EOF
The output is
C:\_D\TEST>cmdfaq
0092010
92010
Or, using a subroutine method
@echo off & setlocal enableextensions
set s_=000
echo %s_%
call :TrimZeros "%s_%" s_
echo %s_%
endlocal & goto :EOF
::
:: =============================================
:TrimZeros Dymmy1 Return_
setlocal enableextensions
echo %~1|findstr [a-zA-Z\.]>nul
if %errorlevel% EQU 0 (endlocal & set "%2=Error" & goto :EOF)
echo %1|findstr [123456789]>nul
if %errorlevel% EQU 0 (
for /f "tokens=* delims=0 " %%a in ('echo %~1') do (
set Return_=%%a)
) else (set Return_=0)
endlocal & set "%2=%Return_%" & goto :EOF
The output will be
C:\_D\TEST>cmdfaq
000
0
Another solution
@echo off & setlocal enableextensions
set s_=009
echo %s_%
:loop
if not "%s_%"=="0" if "%s_:~0,1%"=="0" set s_=%s_:~1%&goto loop
echo %s_%
endlocal & goto :EOF
Alternatively one could use
SET N=009
SET /a N=1%N%-(11%N%-1%N%)/10
ECHO N=%N%
The output will be
N=9
The problem can also be solved with a Visual Basic Script (VBScript). Consider
@echo off & setlocal enableextensions
set s_= 0080
echo %s_%
>"%temp%\tmp$$$.vbs" echo WScript.Echo CLng(%s_%)
for /f %%a in ('cscript //nologo "%temp%\tmp$$$.vbs"') do set s_=%%a
for %%f in ("%temp%\tmp$$$.vbs") do if exist %%f del %%f
echo %s_%
endlocal & goto :EOF
The output will be
C:\_D\TEST>cmdfaq
0080
80
Also see
item #154.