There are two main alternative approaches to extracting information out
of some text string:
- You can break a string into parts with the "SET"
command (see it for more details about the sub-string extraction syntax).
There are some examples:
set TEXT=[ABCD]
set First=%TEXT:~0,1%
set Middle=%TEXT:~1,-1%
set Last=%TEXT:~-1%
echo TEXT STRING: "%Text%"
echo FIRST CHARACTER: "%FIRST%", MIDDLE: "%MIDDLE%", LAST: "%LAST%"
Note that the first byte is at position "0" (not "1").
- An alternative approach is where there are characters
that "delimit" the string you want then you can use the
"FOR" command, for example:
::--- TIME Looks Like "17:55:10.02" (parts delimited by ":" and ".") ---
for /F "tokens=1,2,3,4 delims=:." %%A in ("%TIME%") do set HH=%%A& set MM=%%B& set SS=%%C& set SSFRACTION=%%D
echo TIME: "%TIME%" ==^> HOUR: %HH%, Minute: %MM%, Seconds: %SS% (.%SSFRACTION%)
Sometimes you can convert text you know is there into
a delimiter with string replacement.
The follow script renames files that contain the text
"HWT40 - ", it extracts the text after that and renames the file:
@echo off
for %%F in ("[W*.log") do call :RENAMEIT "%%F"
goto :EOF
::######################
:RENAMEIT
::######################
set ShortNameNameBefore=%~1
set ShortNameNameAfter=%ShortNameNameBefore%
if "%ShortNameNameBefore%" == "" goto :EOF
set Text=%ShortNameNameBefore:HWT40 - =?%
for /F "tokens=2 delims=?" %%A in ("%Text%") do set ShortNameNameAfter=%%A
set CMD=ren "%ShortNameNameBefore%" "%ShortNameNameAfter%"
echo.
echo EXEC: %CMD%
%CMD%
goto :EOF
This is the example, a shortcut was installed to this code
:
@echo off
::@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
:: $Header: C:/DBAREIS/Projects.PVCS/Win32/ScriptingTipsAndTricks/EXAMPLE[cmd].SubString Operations [extract Left, Right, middle].cmd.pvcs 1.0 29 Jun 2014 12:51:22 USER "Dennis" $
::@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
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%"