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.
154} How do I remove leading zeros from a string with script only?
The opposite of item
item #127 How can I
pad leading zeros or like to a variable?
Removing leading zeros, spaces or whatever from a string is somewhat
different from removing the leading zeros from an unsigned integer
explained in FAQ
item #119 "How can I
remove any leading zeros from an unsigned integer?" Also, this time we
would wish not to use any third party programs like sed as in the FAQ
item #79 "How can I trim leading and
trailing spaces?"
Also note that any zeros within the string should not be removed,
only the leading ones! (Removing all the zeros would be trivial
using the
%var:0=% substitution.)
@echo off & setlocal enableextensions
set oldValue=00this is a 0 test
call :RemoveLeadingZeros "%oldValue%" newValue
echo "%oldValue%"
echo "%newValue%"
endlocal & goto :EOF
::
:RemoveLeadingZeros
setlocal enabledelayedexpansion
set s=%~1
for /l %%c in (0,1,255) do (
set si=!s:~%%c,1!
if defined si (
if not "!si!"=="
0" set Flag=true
if defined Flag set return_=!return_!!si!
)
)
endlocal & set "%2=%return_%" & goto :EOF
The output should and will be
C:\_D\TEST>cmdfaq
"00this is a 0 test"
"this is a 0 test"
Let's consider an application for this method from an adapted
question posed in
alt.msdos.batch.nt.
Suppose that there are files like the following in a folder
00000001.TIF
00000002.TIF
00000003.TIF
:
00000010.TIF
00000011.TIF
and we wish to rename those files to be without the leading zeros.
The script can then be written (with echo as a safety) as
@echo off & setlocal enableextensions enabledelayedexpansion
for /f "tokens=* delims=" %%f in ('dir /s /b /a:-d-s-h 0*.TIF') do (
set oldFullPathAndFileName=%%~dpnxf
set oldFileName=%%~nxf
call :RemoveLeadingZeros "!oldFileName!" fileNameWithoutZeros
echo ren "!oldFullPathAndFileName!" "!fileNameWithoutZeros!"
)
::
endlocal & goto :EOF
::
:
RemoveLeadingZeros
setlocal
set s=%~1
for /l %%c in (0,1,255) do (
set si=!s:~%%c,1!
if defined si (
if not "!si!"=="0" set Flag=true
if defined Flag set return_=!return_!!si!
)
)
::
endlocal & set "%2=%return_%" & goto :EOF
The output will be:
C:\_D\TEST>cmdfaq
ren "C:\_D\TEST\00000001.tif" "1.tif"
ren "C:\_D\TEST\00000002.tif" "2.tif"
ren "C:\_D\TEST\00000003.tif" "3.tif"
:
ren "C:\_D\TEST\00000010.tif" "10.tif"
ren "C:\_D\TEST\00000011.tif" "11.tif"