SubString Extraction |
Sometimes you want to extract certain characters out of a bigger string or environment variable, this shows how it can be done:
@echo off @rem *** Copy to "TryMe.cmd" and execute :-) *** setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION cls set WholeString=123456789 set Left20=%WholeString:~0,20% set Left4Chars=%WholeString:~0,4% set Right4Chars=%WholeString:~-4% set The3rdAnd4th=%WholeString:~2,2% set AllButFirst=%WholeString:~1% set AllButLast=%WholeString:~0,-1% set Left20Padded=%WholeString% &rem Add 20 spaces set Left20Padded=%Left20Padded:~0,20%& rem Grab left most to produce passed string echo WholeString = "%WholeString%" echo. echo Left20 = "%Left20%" (note: wasn't padded to 20 characters) echo Left20 (pad) = "%Left20Padded%" echo Left4Chars = "%Left4Chars%" echo Right4Chars = "%Right4Chars%" echo The3rdAnd4th = "%The3rdAnd4th%" echo AllButFirst = "%AllButFirst%" echo AllButLast = "%AllButLast%"
Remove Trailing Spaces and Slash |
Note that the following example uses the code in the "Special Characters (tabs etc)" section to set up the "TAB" environment variable:
set TheDir=C:\TEMP\ &rem ends in spaces and trailing "\"... :RemoveTrailingSpacesTabs if "%TheDir:~-1%" == " " set TheDir=%TheDir:~0,-1%& goto RemoveTrailingSpacesTabs if "%TheDir:~-1%" == "%TAB%" set TheDir=%TheDir:~0,-1%& goto RemoveTrailingSpacesTabs if "%TheDir:~-1%" == "\" set TheDir=%TheDir:~0,-1%