A little nice problem
you can solve it also with carets
Code: Select all
setlocal enableDelayedExpansion
set test=JUNK
echo:!test:~0^,2!
echo:!test:J^=F!
echo.!test:~0^,2!
The cause is the well known command token splitting effect.
When the line is parsed, in phase 2 (special characters ^&<> and so on) also the line is split into two tokens.
The first one is expected as the command the second is the rest of the line.
The tokenizer splits the tokens at "<space>,;=&|<>(", so in your samples the command tokens look like
Code: Select all
echo:!test:~0
echo:!test:J
echo.!test:~0
As the command token and the rest of the line are (delayed) expanded separatly both parts fails to expands.
btw. Even the delayed effect to carets is separated for both parts
Code: Select all
setlocal EnableDelayedExpansion
set a=####
set test=CONTENT
echo:^^^^! ^^^^
echo:^^^^! ^^^^!
echo:!test:~2,3!a!
echo !test:~2,3!a!
----- OUTPUT ----
^ ^^
^ ^
test:~2,3####
NTEa
Ok, but why it fails with an IF !test:~1,2! command
IF,FOR and also REM are detected in phase 2 and activate a special token handler.
IF have special token rules to detect all the different IF-Syntax styles like
IF a==b
if a EQU b
if NOT a==b
if defined var
if exist f
Some of these tokens are not affected by delayed expansion, here only a,b and f are affected.
Code: Select all
set myNot=NOT
set myDefined=defined
set var=content
set indVar=var
set a=#
set b=#
if !a!==!b! echo "==" works
if !a! EQU !b! echo "EQU" works
if NOT a==b echo "NOT" works
if defined !indVar! echo "DEF" works
if !myDefined! var echo SyntaxError
if !myNot! a==b echo SyntaxError
hope it helps
jeb