How to do substitution in variables with EnableDelayedExpansion on in a batch file?

331 Views Asked by At

I asked this question yesterday, but it was marked as duplicate and I was given a link to a question that discusses something similar, but NOT variable substitution and substrings specifically, so I'm posting it again.

I am trying to do variable substitution with delayed expansion variables

Normally, I'd have something like this:

REM Sub 123 for bcd
SET Myvar=abcdefg
SET MyNewVar=%MyVar:bcd=123%
echo %MyNewVar%

REM Just get all but the last 2 chars of the string
SET MyShortVar=%Myvar:~0,-2%
echo %MyShortVar%

Based on this article (Variables Are Not Behaving As Expected), I tried this:

SET MyShortVar=%%Myvar:~0,-1%%
ECHO MyShortVar=[%MyShortVar%] or [!MyShortVar!]

and got this output:

MyShortVar=[%Myvar:~0,-1%] or [%Myvar:~0,-1%]

But how do I do this when using variables where I have to use the bang symbol because of Delayed Expansion?

1

There are 1 best solutions below

2
cashonly On

Found my answer here: Why can I not get a substring of a delayed expansion variable in an if statement?

BY using the ! instead of % for string substitution AND enclosing that in double quotes, it worked. As in this example from an answer to that question:

setLocal enableDelayedExpansion
set test=testString
if "!test:~0,4!" == "test" echo Success