I know how to do a literal string substitution in a batch script. However, I have a specific situation where I need to substitute the value of a numeric variable
This is the script:
setlocal enableextensions enabledelayedexpansion
set /A L=2
:L1
if %L% EQU 0 goto :EOF
set STRING="THIS IS # TEST"
SET NEW=%STRING:#=%%L%
echo %NEW%
set /A L=%L% - 1
goto L1
I want it to display this:
THIS IS 2 TEST
THIS IS 1 TEST
But it ends up diplaying this instead:
THIS IS TEST2
THIS IS TEST1
Any tips on how to get it to do what I need?
Thanks.
Even the solutions of aphoria and Bali C will work, it's better to use
set "NEW=!STRING:#=%L%!"
As then the replacement will be done in the delayed expansion phase and not in the percent expansion phase.
This will also work with exclamation marks and carets in STRING
@echo off
set L=2
set "String=This is # test!"
setlocal EnableDelayedExpansion
set "NEW=!STRING:#=%L%!"
echo !NEW!
Your almost there, just change
SET NEW=%STRING:#=%%L%
to
SET NEW=%STRING:#=!L!%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With