Batch script (Windows) replacing a string with a twist

I know how to do a literal string replacement in a script package. 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 /AL=2 :L1 if %L% EQU 0 goto :EOF set STRING="THIS IS # TEST" SET NEW=%STRING:#=%%L% echo %NEW% set /AL=%L% - 1 goto L1 

I want it to display this:

 THIS IS 2 TEST THIS IS 1 TEST 

But this ends up being instead:

 THIS IS TEST2 THIS IS TEST1 

Any tips on how to get him to do what I need?

Thanks.

+4
source share
5 answers

Almost everything, just change

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

to

 SET NEW=%STRING:#=!L!% 
+3
source

Even the aphoria and Bali C solutions will work, it is better to use

 set "NEW=!STRING:#=%L%!" 

As then, the replacement will be performed in the delayed expansion phase, and not in the percentage expansion phase.

This will also work with exclamation marks and carriages in STRING

 @echo off set L=2 set "String=This is # test!" setlocal EnableDelayedExpansion set "NEW=!STRING:#=%L%!" echo !NEW! 
+7
source

You need to use !L! to use pending extension.

 @ECHO OFF SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION SET /AL=2 :L1 IF !L! EQU 0 goto :EOF SET STRING=THIS IS # TEST SET NEW=%STRING:#=!L!% ECHO %NEW% SET /AL=!L! - 1 GOTO L1 

In fact, you do not need to use !L! everywhere, only on the line SET NEW=%STRING:#!L!% . I used it everywhere for visual consistency.

+2
source

Just for fun. Here's how to do this without delaying expansion. :)

Using the call command to double expand variables. Use the double percent %% around the variable to evaluate the second. Single percent % around the variable to evaluate first.

 setlocal EnableExtensions set /AL=2 :L1 if %L% EQU 0 goto :EOF set "STRING=THIS IS # TEST" call set "NEW=%%STRING:#=%L%%%" echo %NEW% set /AL=%L% - 1 goto L1 
+2
source

You can also use STRING as a "formatted string" by placing the desired variables in the right places, enclosed in exclamation points. Thus, further replacement of values ​​is not required, just display the format string in the usual way:

 rem Define the "format string" with Delayed Expansion disabled: set STRING=THIS IS !L! TEST setlocal enableextensions enabledelayedexpansion set /AL=2 :L1 if %L% EQU 0 goto :EOF echo %STRING% set /AL=L - 1 goto L1 

Or without Delayed \ Expansion:

 set STRING=THIS IS %%L%% TEST set /AL=2 :L1 if %L% EQU 0 goto :EOF call echo %STRING% set /AL=L - 1 goto L1 

Antonio

+2
source

All Articles