1

Yes I know - a lot of information in Net. But. Let's try what what they wrote.

Unfortunately this will not work because the :~ syntax expects a value not a variable. To get around this use the CALL command like this:

SET _startchar=2
SET _length=1
SET _donor=884777
CALL SET _substring=%%_donor:~%_startchar%,%_length%%%
ECHO (%_substring%)

Ok. My Example.

Tell me please - what I'm doing wrong?

4
  • Note: the SS64 example doesn't work either. Commented Dec 27, 2017 at 8:26
  • 1
    Put everything in one .cmd file and it works Commented Dec 27, 2017 at 8:33
  • The batch file parser works slightly different than the command line parser; the former converts %% to % but the latter does not, hence you cannot use the code in command prompt but in a batch file only. Refer to this: How does the Windows Command Interpreter (CMD.EXE) parse scripts? Commented Dec 27, 2017 at 9:19
  • This type of management is fully described at this answer, although the topic is different... Commented Dec 27, 2017 at 14:15

1 Answer 1

1

1) You can try with delayed expansion:

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777
SET _substring=!_donor:~%_startchar%,%_length%!
ECHO (%_substring%)

2) to make it work with CALL SET you need double % (but it will be slower than the first approach):

@Echo off

::setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777
call SET _substring=%%_donor:~%_startchar%,%_length%%%
ECHO (%_substring%)

3) You can use delayed expansion and for loop. It can be useful if there are nested bracket blocks and the _startchar and _length are defined there.Still will be faster than CALL SET:

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777


for /f "tokens=1,2 delims=#" %%a in ("%_startchar%#%_length%") do (
    SET _substring=!_donor:~%%a,%%b!
)

ECHO (%_substring%)

4) you can use subroutine and delayed expansion :

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777


call :subString %_donor% %_startchar% %_length% result
echo (%result%)

exit /b %errorlevel%

:subString %1 - the string , %2 - startChar , %3 - length , %4 - returnValue
setlocal enableDelayedExpansion
set "string=%~1"
set res=!string:~%~2,%~3!

endlocal & set "%4=%res%"

exit /b %errorlevel%
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.