DOS - String Operations

Basic string operations in batch like you are used to from other programming languages.



TOP
2008-02-27

:lTrim - strips white spaces (or other characters) from the beginning of a string

Description: call:lTrim string char
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
:lTrim string char -- strips white spaces (or other characters) from the beginning of a string
::                 -- string [in,out] - string variable to be trimmed
::                 -- char   [in,opt] - character to be trimmed, default is space
:$created 20060101 :$changed 20080227 :$categories StringManipulation
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
call set "string=%%%~1%%"
set "charlist=%~2"
if not defined charlist set "charlist= "
for /f "tokens=* delims=%charlist%" %%a in ("%string%") do set "string=%%a"
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET "%~1=%string%"
)
EXIT /b

TOP
2008-02-19

:rTrim - strips white spaces (or other characters) from the end of a string

Description: call:rTrim string char max
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
:rTrim string char max -- strips white spaces (or other characters) from the end of a string
::                     -- string [in,out] - string variable to be trimmed
::                     -- char   [in,opt] - character to be trimmed, default is space
::                     -- max    [in,opt] - maximum number of characters to be trimmed from the end, default is 32
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
call set string=%%%~1%%
set char=%~2
set max=%~3
if "%char%"=="" set char= &rem one space
if "%max%"=="" set max=32
for /l %%a in (1,1,%max%) do if "!string:~-1!"=="%char%" set string=!string:~0,-1!
( ENDLOCAL & REM RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%string%
)
EXIT /b

TOP
2008-03-20

:StartsWith - Tests if a text starts with a given string

Description: call:StartsWith text string
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:StartsWith text string -- Tests if a text starts with a given string
::                      -- [IN] text   - text to be searched
::                      -- [IN] string - string to be tested for
:$created 20080320 :$changed 20080320 :$categories StringOperation,Condition
:$source http://www.dostips.com
SETLOCAL
set "txt=%~1"
set "str=%~2"
if defined str call set "s=%str%%%txt:*%str%=%%"
if /i "%txt%" NEQ "%s%" set=2>NUL
EXIT /b

TOP
2010-11-16

:strLen - returns the length of a string

Description: call:strLen string len
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
:strLen string len -- returns the length of a string
::                 -- string [in]  - variable name containing the string being measured for length
::                 -- len    [out] - variable to be used to return the string length
:: Many thanks to 'sowgtsoi', but also 'jeb' and 'amel27' dostips forum users helped making this short and efficient
:$created 20081122 :$changed 20101116 :$categories StringOperation
:$source http://www.dostips.com
(   SETLOCAL ENABLEDELAYEDEXPANSION
    set "str=A!%~1!"&rem keep the A up front to ensure we get the length and not the upper bound
                     rem it also avoids trouble in case of empty string
    set "len=0"
    for /L %%A in (12,-1,0) do (
        set /a "len|=1<<%%A"
        for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"
    )
)
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" SET /a %~2=%len%
)
EXIT /b

TOP
2008-02-19

:toCamelCase - converts a string to camel case

Description: call:toCamelCase str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
:toCamelCase str -- converts a string to camel case
::               -- str [in,out] - valref of string variable to be converted
:$created 20080219 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
REM make all lower case
for %%a in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i"
            "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r"
            "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z"
            "Ä=ä" "Ö=ö" "Ü=ü") do (
    call set "%~1=%%%~1:%%~a%%"
)
call set "%~1= %%%~1%%"
REM make first character upper case
for %%a in (" a=A" " b=B" " c=C" " d=D" " e=E" " f=F" " g=G" " h=H" " i=I"
            " j=J" " k=K" " l=L" " m=M" " n=N" " o=O" " p=P" " q=Q" " r=R"
            " s=S" " t=T" " u=U" " v=V" " w=W" " x=X" " y=Y" " z=Z"
            " ä=Ä" " ö=Ö" " ü=Ü") do (
    call set "%~1=%%%~1:%%~a%%"
)
call set "%~1=%%%~1: =%%"
EXIT /b

TOP
2008-02-19

:toLower - converts uppercase character to lowercase

Description: call:toLower str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:toLower str -- converts uppercase character to lowercase
::           -- str [in,out] - valref of string variable to be converted
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
for %%a in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i"
            "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r"
            "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z" "Ä=ä"
            "Ö=ö" "Ü=ü") do (
    call set %~1=%%%~1:%%~a%%
)
EXIT /b

TOP
2008-02-19

:toUpper - converts lowercase character to uppercase

Description: call:toUpper str
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:toUpper str -- converts lowercase character to uppercase
::           -- str [in,out] - valref of string variable to be converted
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
if not defined %~1 EXIT /b
for %%a in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I"
            "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R"
            "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z" "ä=Ä"
            "ö=Ö" "ü=Ü") do (
    call set %~1=%%%~1:%%~a%%
)
EXIT /b

TOP
2008-02-19

:Trim - strip white spaces (or other characters) from the beginning and end of a string

Description: call:Trim string char max
Dependencies: :lTrim, :rTrim
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
:Trim string char max -- strip white spaces (or other characters) from the beginning and end of a string
::                    -- string [in,out] - string variable to be trimmed
::                    -- char   [in,opt] - character to be trimmed, default is space
::                    -- max    [in,opt] - maximum number of characters to be trimmed from the end, default is 32
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
call:lTrim "%~1" "%~2"
call:rTrim "%~1" "%~2" "%~3"
EXIT /b

TOP
2008-02-23

:trimSpaces - trims spaces around string variable

Description: call:trimSpaces varref
Dependencies: :trimSpaces2
Script:
1.
2.
3.
4.
5.
6.
:trimSpaces varref -- trims spaces around string variable
::                 -- varref [in,out] - variable to be trimmed
:$created 20060101 :$changed 20080223 :$categories StringManipulation
:$source http://www.dostips.com
call call:trimSpaces2 %~1 %%%~1%%
EXIT /b

TOP
2008-02-19

:trimSpaces2 - trims spaces around string and assigns result to variable

Description: call:trimSpaces2 retval string
Script:
1.
2.
3.
4.
5.
6.
7.
:trimSpaces2 retval string -- trims spaces around string and assigns result to variable
::                         -- retvar [out] variable name to store the result in
::                         -- string [in]  string to trim, must not be in quotes
:$created 20060101 :$changed 20080219 :$categories StringManipulation
:$source http://www.dostips.com
for /f "tokens=1*" %%A in ("%*") do set "%%A=%%B"
EXIT /b

TOP
2008-02-19

:Unique - returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc

Description: call:Unique ret
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
:Unique ret -- returns a unique string based on a date-time-stamp, YYYYMMDDhhmmsscc
::          -- ret    [out,opt] - unique string
:$created 20060101 :$changed 20080219 :$categories StringOperation,DateAndTime
:$source http://www.dostips.com
SETLOCAL
for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('"echo.|date"') do (
    for /f "tokens=1-3 delims=/.- " %%A in ("%date:* =%") do (
        set %%a=%%A&set %%b=%%B&set %%c=%%C))
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
for /f "tokens=1-4 delims=:. " %%A in ("%time: =0%") do @set UNIQUE=%yy%%mm%%dd%%%A%%B%%C%%D
ENDLOCAL & IF "%~1" NEQ "" (SET %~1=%UNIQUE%) ELSE echo.%UNIQUE%
EXIT /b

TOP
2008-01-01

Align Right - Align text to the right i.e. to improve readability of number columns

Description: Add leading spaces to a string to make sure the output lines up. I.e. for variables no longer than 8 characters add 8 spaces at the front and then show only the last 8 characters of the variable.
Script:
1.
2.
3.
4.
5.
6.
set x=3000
set y=2
set x=        %x%
set y=        %y%
echo.X=%x:~-8%
echo.Y=%y:~-8%
Script Output:
 DOS Script Output
X=    3000
Y=       2

TOP
2008-01-01

Left String - Extract characters from the beginning of a string

Description: Similar to the Left function in VB a batch script can return a specified number of characters from the left side of a string by specifying a substring for an expansion given a position of 0 and a length using :~ while expanding a variable content. The example shows how to return the first 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%
Script Output:
 DOS Script Output
politic
poli

TOP
2008-01-01

Map and Lookup - Use Key-Value pair list to lookup and translate values

Description: This example shows an approach to map a name of a month into it`s corresponding two digit number. The key-value pairs are listed in the map variable separated by semicolon. Key and value itself are separated by one dash character. Same can be used to tranlate a day-of-the-week short string into a day-of-the-week long string by changing the map content only.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
REM ---- Example 1: Translate name of month into two digit number ----
SET v=Mai

SET map=Jan-01;Feb-02;Mar-03;Apr-04;Mai-05;Jun-06;Jul-07;Aug-08;Sep-09;Oct-10;Nov-11;Dec-12
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

ECHO.%v%


REM ---- Example 2: Translate abbreviation into full string ----
SET v=sun

set map=mon-Monday;tue-Tuesday;wed-Wednesday;thu-Thursday;fri-Friday;sat-Saturday;sun-Sunday
CALL SET v=%%map:*%v%-=%%
SET v=%v:;=&rem.%

  ECHO.%v%
Script Output:
 DOS Script Output
05
  Sunday

TOP
2008-01-01

Mid String - Extract a Substring by Position

Description: Similar to the Mid function in VB a batch script can return a specified number of characters from any position inside a string by specifying a substring for an expansion given a position and length using :~ while expanding a variable content. The example here shows how to extract the parts of a date.
Script:
1.
2.
3.
4.
5.
echo.Date   : %date%
echo.Weekday: %date:~0,3%
echo.Month  : %date:~4,2%
echo.Day    : %date:~7,2%
echo.Year   : %date:~10,4%
Script Output:
 DOS Script Output
Date   : Sat 03/11/2006
Weekday: Sat
Month  : 03
Day    : 11
Year   : 2006

TOP
2008-01-01

Remove - Remove a substring using string substitution

Description: The string substitution feature can also be used to remove a substring from another string. The example shown here removes all occurrences of "the " from the string variable str.
Script:
1.
2.
3.
4.
set str=the cat in the hat
echo.%str%
set str=%str:the =%
echo.%str%
Script Output:
 DOS Script Output
the cat in the hat
cat in hat

TOP
2008-01-01

Remove both Ends - Remove the first and the last character of a string

Description: Using :~1,-1 within a variable expansion will remove the first and last character of the string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~1,-1%
echo.%str%
Script Output:
 DOS Script Output
politic
oliti

TOP
2008-01-01

Remove Spaces - Remove all spaces in a string via substitution

Description: This script snippet can be used to remove all spaces from a string.
Script:
1.
2.
3.
4.
set str=      word       &rem
echo."%str%"
set str=%str: =%
echo."%str%"
Script Output:
 DOS Script Output
"      word       "
"word"

TOP
2008-01-01

Replace - Replace a substring using string substitution

Description: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences "teh" misspellings with "the" in the string variable str.
Script:
1.
2.
3.
4.
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%
Script Output:
 DOS Script Output
teh cat in teh hat
the cat in the hat

TOP
2008-01-01

Right String - Extract characters from the end of a string

Description: Similar to the Right function in VB a batch script can return a specified number of characters from the right side of a string by specifying a substring for an expansion given a negative position using :~ while expanding a variable content. The example shows how to return the last 4 characters of a string.
Script:
1.
2.
3.
4.
set str=politic
echo.%str%
set str=%str:~-4%
echo.%str%
Script Output:
 DOS Script Output
politic
itic

TOP
2008-01-01

Split String - Split a String, Extract Substrings by Delimiters

Description: Use the FOR command to split a string into parts. The example shows how to split a date variable into its parts.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
echo.-- Split off the first date token, i.e. day of the week
for /f %%a in ("%date%") do set d=%%a
echo.Date   : %date%
echo.d      : %d%
echo.

echo.-- Split the date into weekday, month, day, and year, using slash and space as delimiters
for /f "tokens=1,2,3,4 delims=/ " %%a in ("%date%") do set wday=%%a&set month=%%b&set day=%%c&set year=%%d
echo.Weekday: %wday%
echo.Month  : %month%
echo.Day    : %day%
echo.Year   : %year%
Script Output:
 DOS Script Output
-- Split off the first date token, i.e. day of the week
Date   : Thu 12/02/2005
d      : Thu

-- Split the date into weekday, month, day, and year, using slash and space as delimiters
Weekday: Thu
Month  : 12
Day    : 02
Year   : 2005

TOP
2008-02-26

String Concatenation - Add one string to another string

Description: This example shows how to add two strings in DOS.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set "str1=Hello"
  set "str2=World"

  set "str3=%str1%%str2%"
  set "str4=%str1% %str2%"
  set "str1=%str1% DOS %str2%"

  echo.%str3%
  echo.%str4%
  echo.%str1%
Script Output:
 DOS Script Output
HelloWorld
  Hello World
  Hello DOS World

TOP
2008-04-28

Trim Left - Trim spaces from the beginning of a string via "FOR" command

Description: Use the FOR command to trim spaces at the beginning of a variable. In this example the variable to be trimmed is str.
Script:
1.
2.
3.
4.
set str=               15 Leading spaces to truncate
echo."%str%"
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a
echo."%str%"
Script Output:
 DOS Script Output
"               15 Leading spaces to truncate"
"15 Leading spaces to truncate"

TOP
2008-01-01

Trim Quotes - Remove surrounding quotes via FOR command

Description: The FOR command can be used to safely remove quotes surrounding a string. If the string does not have quotes then it will remain unchanged.
Script:
1.
2.
3.
4.
set str="cmd politic"
echo.%str%
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a
echo.%str%
Script Output:
 DOS Script Output
"cmd politic"
cmd politic

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via "FOR" command

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use a FOR loop to trim up to 31 spaces from the end of a string. It assumes that Delayed Expansion is enabled.
Script:
1.
2.
3.
4.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!
echo."%str%"
Script Output:
 DOS Script Output
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"

TOP
2008-01-01

Trim Right - Trim spaces from the end of a string via substitution

Description: Trimming spaces at the end of a variable seems a little tricky. The following example shows how to use the string substitution feature to trim up to 31 spaces from the end of a string. It assumes that the string to be trimmed never contains two hash "##" characters in a row.
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
set str=15 Trailing Spaces to truncate               &rem
echo."%str%"
set str=%str%##
set str=%str:                ##=##%
set str=%str:        ##=##%
set str=%str:    ##=##%
set str=%str:  ##=##%
set str=%str: ##=##%
set str=%str:##=%
echo."%str%"
Script Output:
 DOS Script Output
"15 Trailing Spaces to truncate               "
"15 Trailing Spaces to truncate"