Badt_Paul
Badt_Paul

Reputation: 81

Variables: extract part of a variable

this is not a question, but follow up on this article: [http://ss64.com/nt/syntax-substring.html ]. The problem I had with that routine, was that it did not work within a FOR loop. So I got in contact with one of the authors, and therefore #Ritchie Lawrence# gets full credit for this subroutine:

@echo off

echo 123456789-1-3>strManip.txt
echo 123456789-2-3>>strManip.txt
echo 123456789-3-3>>strManip.txt
echo 123456789-3-4>>strManip.txt
echo 123456789-3-5>>strManip.txt
echo 123456789-3-6>>strManip.txt

Setlocal EnableDelayedExpansion
set MyResult=
for /f "tokens=1-3 delims=-" %%a in (strManip.txt) do (

   call :strManip %%a %%b %%c MyResult
   echo Mainr:[!MyResult!]
)
endlocal
del strManip.txt >nul
pause
exit

rem *** subroutine
:strManip
setlocal
set string=%1
set start=%2
set end=%3

call call set _string=%%string:~%start%,%end%%%

echo Subr:{%_string%}

endlocal & (set %4=%_string%)
goto :EOF

Output:
Subr:{234}
Mainr:[234]
Subr:{345}
Mainr:[345]
Subr:{456}
Mainr:[456]
Subr:{4567}
Mainr:[4567]
Subr:{45678}
Mainr:[45678]
Subr:{456789}
Mainr:[456789]
Press any key to continue . . .

Obviously, you can/could apply this technique in other situations as well (not just in string manipulation, I mean).

Upvotes: 1

Views: 125

Answers (1)

foxidrive
foxidrive

Reputation: 41234

As you are using delayed expansion anyway, it can be done like this:

@echo off
(
echo 123456789-1-3
echo 123456789-2-3
echo 123456789-3-3
echo 123456789-3-4
echo 123456789-3-5
echo 123456789-3-6
)>strManip.txt

Setlocal EnableDelayedExpansion
for /f "tokens=1-3 delims=-" %%a in (strManip.txt) do (
   set "MyResult=%%a"
   echo Mainr:[!MyResult:~%%b,%%c!]
)
endlocal
del strManip.txt >nul
pause

Upvotes: 3

Related Questions