Reputation: 6255
I'm trying to substring a certain string using variables as indexes:
call :subStrFunction 0 1 test
:subStrFunction
set _startchar =%~1
set _endchar =%~2
set _stringInput=%~3
::tried with this
CALL SET subStr=!_stringInput:~%_startchar%,%_endchar%!
::and this (found on http://ss64.com/)
::CALL SET subStr=%%_stringInput:~%_startchar%,%_endchar%%%
::end this
::SET _substring=%_stringInput:~%_startchar %,%_endchar %
echo substring %subStr%
but none of them works >,<
Thx in advance! :D
UPDATE: SOLVED by adding setLocal enableDelayedExpansion
Upvotes: 2
Views: 179
Reputation: 435
I reworked the batch file to allow for either 1 or both parameters for the sub-string feature.
The turn value will be stored in an environment variable called {str_Return} and will be visible outside of the setlocal environment. A second environment variable called {bolReturn} will be set to {T} for a successful result and {F} if at least the start position was not supplied or there was an error with the sub-string command.
@Echo Off
call :subStrFunction test 0 1
If "%bolReturn%" EQU "T" (
Echo %str_Return%
) Else (
Echo Command was not successful
)
pause
:subStrFunction
setLocal enableDelayedExpansion
REM String variable needs to be first
set stringInput=%~1
REM If only 1 number is given
If "%~2" EQU "" Goto :l_Missing_Param
If "%~3" EQU "" Goto :l_1_Operand
REM Start and stop parameters given
Set "str_Result=!stringInput:~%~2,%~3!"
If [%ERRORLEVEL%] NEQ [0] Goto :l_Exeuction_Error
Goto :l_Return_Value
:l_1_Operand
REM Start parameter given
Set "str_Result=!stringInput:~%~2!"
If [%ERRORLEVEL%] NEQ [0] Goto :l_Exeuction_Error
Goto :l_Return_Value
:l_Missing_Param
Echo.
Echo You did not provide the correct number of parameters
REM Set Exit value to F for an imcomplete execution
EndLocal & Set bolReturn=F
Goto :EOF
:l_Exeuction_Error
Echo.
Echo An unspecified error has occured!
REM Set Exit value to F for an imcomplete execution
EndLocal & Set bolReturn=F
Goto :EOF
:l_Return_Value
REM Store result value in stable variable
EndLocal & Set "str_Return=%str_Result%"
REM Set Exit value to T for a complete execution
Set bolReturn=T
Goto :EOF
You can either use this as a sub-routine or for a seperate batch file entirely.
p.s. If you copy this code into your own batch file, make very sure that each quote {"} used is an actual quote and not one of the curly quotes or the batch file will fail.
Upvotes: 1