trashgenerator
trashgenerator

Reputation: 470

Batch. Get substring

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?

Upvotes: 1

Views: 4119

Answers (1)

npocmaka
npocmaka

Reputation: 57252

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%

Upvotes: 1

Related Questions