Dos String editing

Basic string manipulation for batch files.

Align Right - Right Align text

Add leading spaces to a string. For variables no longer than 8 characters add 8 spaces at the front and then show only the last 8 characters of the variable.

set x=3000
set x= %x%
echo.X=%x:~-8%

Left String - Extract characters from the beginning of a string

Return a specified number of characters from the left side of a string - example return first 4 characers.

set str=something
set str=%str:~0,4%

Mid String - Extract a Substring by Position

Return a specified number of characters from any position inside a string

echo.Month : %date:~4,2%
echo.Day : %date:~7,2%
echo.Year : %date:~10,4%

Remove - Remove a substring using string substitution

The string substitution feature can be used to remove a substring from another string.

set str=the cat in the hat
set str=%str:the =%

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

Using :~1,-1 within a variable expansion will remove the first and last character of the string.

set str=something
set str=%str:~1,-1%

Remove Spaces- Remove all spaces in a string via substitution

This script snippet can be used to remove all spaces from a string.

set str= word &rem
set str=%str: =%

Replace- Replace a substring using string substitution

Replace a substring with another string use the string substitution feature.

set str=teh cat in teh hat
set str=%str:teh=the%

Right String- Extract characters from the end of a string

The example shows how to return the last 4 characters of a string.

set str=something
set str=%str:~-4%

String Concatenation- Add one string to another string

Add two strings in DOS.

set "str3=%str1% %str2%"

For - Command tricks

Use the FOR command to split a string into parts. Split a String, Extract Substrings by Delimiters

for /f %%a in ("%date%") do set d=%%a
for /f "tokens=1,2,3,4 delims=/ " %%a in ("%date%") do set wday=%%a&set month=%%b&set day=%%c&set year=%%d

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

set str= 15 Leading spaces to truncate
for /f "tokens=* delims= " %%a in ("%str%") do set str=%%a

Remove surrounding quotes via FOR command

set str="cmd something"
for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a

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

set str=15 Trailing Spaces to truncate &rem
for /l %%a in (1,1,31) do if "!str:~-1!"==" " set str=!str:~0,-1!