Close this search box.

Useful DOS Batch functions: Substring() and Length()

Recently I needed to determine the length of a string and perform a Substring operation on a variable in a DOS Batch (.bat) file.  (Yes, people still use DOS batch files!)

After some Googling and some playing around I came up with the following functions. 

:: extracts the substring from string starting at startIndex for the specified length 
 SET string=%2%
 SET startIndex=%3%
 SET length=%4%
 if "%4" == "0" goto :noLength
 CALL SET _substring=%%string:~%startIndex%,%length%%%
 goto :substringResult
 CALL SET _substring=%%string:~%startIndex%%%
 set "%~1=%_substring%"
::returns the length of the string specified in %2 and stores it in %1
set #=%2%
set length=0
if defined # (set #=%#:~1%&set /A length += 1&goto stringLengthLoop)
::echo the string is %length% characters long!
set "%~1=%length%"

To call them:


:: get the lenth of the sConfigFileRoot
call:StrLength length %sCFR%
:: extract the suffix
call:Substring suffix,%fileroot%,%length%,0
posted on Saturday, January 30, 2010 2:26 PM
This article is part of the GWB Archives. Original Author: SoftwareDoneRight

Related Posts