Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file: Variable within a variable

I have a complex string I'm trying to parse. I have a short subroutine to fine the index of two specific characters, and I need the string in between. So the question is: How do I use variables inside string manipulation of another variable?

Here's some sample code:

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
echo %str:~%start%,%end%%

How do I get the second echo to display what the first echo displays? (right now second echo is just showing what I want, it'll crash as is)

like image 436
user2370851 Avatar asked Mar 25 '26 18:03

user2370851


1 Answers

@ECHO off

set start=2
set end=5
set str=Hello World

setlocal enableDelayedExpansion
echo %str:~2,5%
echo !str:~%start%,%end%!
endlocal

or (the worst way)

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
call echo %%str:~%start%,%end%%%

or (can be used if start and end definition and the substringing are all in brackets context)

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
setlocal enableDelayedExpansion
for /f "tokens=1,2" %%a in ("%start% %end%") do echo !str:~%%a,%%b!
endlocal

or (also a bad way)

@ECHO off

set start=2
set end=5
set str=Hello World

call :substr "%str%" %start% %end%
goto :eof

:substr
setlocal enableDelayedExpansion
set "_str=%~1"
echo !_str:~%2,%3!
rem without delayedExpansion
rem call echo %%_str:~%2,%3%%
endlocal
goto :eof
like image 54
npocmaka Avatar answered Mar 28 '26 18:03

npocmaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!