Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script (Windows) string substitution with a twist

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.

like image 960
Neil Weicher Avatar asked Dec 05 '22 13:12

Neil Weicher


2 Answers

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!
like image 108
jeb Avatar answered Dec 07 '22 01:12

jeb


Your almost there, just change

SET NEW=%STRING:#=%%L%

to

SET NEW=%STRING:#=!L!%
like image 33
Bali C Avatar answered Dec 07 '22 01:12

Bali C