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?

alprosoja
  • 15
  • 4
trashgenerator
  • 412
  • 6
  • 19
  • Note: the SS64 example doesn't work either. –  Dec 27 '17 at 08:26
  • 1
    Put everything in one .cmd file and it works – SBF Dec 27 '17 at 08: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?](https://stackoverflow.com/a/4095133) – aschipfl Dec 27 '17 at 09:19
  • This type of management is fully described at [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990), although the topic is different... – Aacini Dec 27 '17 at 14:15

1 Answers1

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%
npocmaka
  • 51,748
  • 17
  • 123
  • 166