DOS - String Manipulation

From KlavoWiki
Jump to navigationJump to search

For a comprehensive list DOS - String Manipulation

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 5characters of the variable.

set x=3000
set y=2
set x=        %x%
set y=        %y%
echo.X=%x:~-5%
echo.Y=%y:~-5%

Result

X= 3000
Y=    2

Left String

Extract characters from the beginning of a string.
Description: Similar to the Left function, 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 3 characters of a string.

set str=eucalyptus
echo %str%
set str=%str:~0,3%
echo %str%

Result

eucalyptus
euc

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.

echo Date    : %date%
echo Weekday : %date:~0,3%
echo Day     : %date:~7,2%
echo Month   : %date:~4,2%
echo Year    : %date:~10,4%

Result

Date    : Mon 18/06/2012
Weekday : Mon
Day     : 06
Month   : 18
Year    : 2012

For a typical filename for a backup:

name-%date:~10,4%%date:~4,2%%date:~7,2%-%time:~0,2%%time:~3,2%.txt