Search
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. 

:Substring
::Substring(retVal,string,startIndex,length)
:: 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
 :noLength
 CALL SET _substring=%%string:~%startIndex%%%
 :substringResult
 set "%~1=%_substring%"
GOTO :EOF
 
:StrLength
::StrLength(retVal,string)
::returns the length of the string specified in %2 and stores it in %1
set #=%2%
set length=0
:stringLengthLoop
if defined # (set #=%#:~1%&set /A length += 1&goto stringLengthLoop)
::echo the string is %length% characters long!
set "%~1=%length%"
GOTO :EOF
 

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