Search code examples
windowsbatch-filecmd

How to use a variable in "LEFT()" function in batch script


I'm afraid many would find this to be a dumb question...

@ECHO off
SET str=HelloWorld
ECHO.%str%
SET str=%str:~0,5%
ECHO %str%

The output is as expected:

HelloWorld
Hello

But this code below ...

@ECHO off
SET str=HelloWorld
ECHO.%str%
SET /A val=5
SET str=%str:~0,val%
ECHO.%str%

I'm intuitively expecting the same result but its output is strange to me.

HelloWorld
str:~0,val  

Would anyone care to share why and how this can be fixed?

Thank you.


Solution

  • You have to use callcommand which cause doubled set command execution. Variable %val% will evaluate in first set runtime which caused there will be a number in second runtime. Percent signs have to be doubled in this way call SET str=%%str:~0,%val%%%