Thursday, October 24, 2013

CMD DOS SET with colon and tilde for SUBSTRING

CMD DOS SET with colon and tilde for SUBSTRING


This example shows the meaning of the syntax of a SET statement with a tilde to specify starting and ending position to get a substring.  


Test7.cmd = regular expansion
Test8.cmd = delayed expansion



Test7.cmd:


@echo off
SET start=4
SET length=9
rem            123456789
rem        123456789abcdef
SET string=The quick brown fox jumps over the lazy dog
rem            |        |
echo %string%
rem note that the set variable must be different
CALL SET substring=%%string:~%start%,%length%%%
ECHO %substring%
goto:eof



Output:


C:\testscripts>test7
The quick brown fox jumps over the lazy dog
quick bro


C:\testscripts>


original source:  ss64.com - example
ss64.com had an example but did not explain it - this tries to explain it.


test8.cmd:
SETLOCAL ENABLEDDELAYEDEXPANSION version


This example takes text from position 2 and picks up 5 characters


@echo off
cls
SETLOCAL enabledelayedexpansion
set vwb_suffix=Flightoffancy
echo vwb_suffix 1 = !vwb_suffix!
set startIndex=2
set length=5
rem note that the set variable must be different
CALL SET _vwb_suffix=!vwb_suffix:~%startIndex%,%length%!
echo _vwb_suffix 2 = !_vwb_suffix!
goto:eof




Output:



vwb_suffix 1 = Flightoffancy
_vwb_suffix 2 = ighto


No comments:

Post a Comment