Nested variables

  • Thread starter Thread starter User
  • Start date Start date
U

User

I have to replace a substring on a string.
On "MyStrVar" variable I want to search "MySearchStr" variable's value and
replace it with the "MyNewStr" variable's value.
I've tryed the following but don't work:

Set MyNewVar=%MyStrVar:%MySearchStr%=%MyNewStr%%

Any idea how to use nested variables?
 
I have to replace a substring on a string.
On "MyStrVar" variable I want to search "MySearchStr" variable's value and
replace it with the "MyNewStr" variable's value.
I've tryed the following but don't work:

Set MyNewVar=%MyStrVar:%MySearchStr%=%MyNewStr%%

Any idea how to use nested variables?

You can use two approaches, the first with CALL SET and the
second using Delayed Variable Expansion (Windows 2000/XP):

(a) CALL SET

This expands a line twice. Note carefully how %% and % combinations
are used to allow the variables to be expanded in order at each level.

Lines that don't begin with two spaces have wrapped accidentally
====Begin cut-and-paste (omit this line)
@ECHO OFF
SETLOCAL
SET MyStrVar=Buffy the Vampire Slayer
SET MySearchStr=Vampire Slayer
SET MyNewStr=Chosen One
CALL SET MyNewVar=%%MyStrVar:%MySearchStr%=%MyNewStr%%%
ECHO [%MyStrVar%] becomes [%MyNewVar%]

====End cut-and-paste (omit this line)
Simulated Win2000 for study/demo use. Cut-and-paste as Batch text file.
Batch file troubleshooting: http://www.allenware.com/find?UsualSuspects

Screen capture shows operation:

============Screen capture Windows 2000 simulated in Win95
C:\WORK>demo1
[Buffy the Vampire Slayer] becomes [Buffy the Chosen One]

C:\WORK>
============End screen capture

(b) Delayed variable expansion

!Variables! are expanded after %Variables%

Lines that don't begin with two spaces have wrapped accidentally
====Begin cut-and-paste (omit this line)
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET MyStrVar=Buffy the Vampire Slayer
SET MySearchStr=Vampire Slayer
SET MyNewStr=Chosen One
SET MyNewVar=!MyStrVar:%MySearchStr%=%MyNewStr%!
ECHO [%MyStrVar%] becomes [%MyNewVar%]

====End cut-and-paste (omit this line)
Simulated Win2000 for study/demo use. Cut-and-paste as Batch text file.
Batch file troubleshooting: http://www.allenware.com/find?UsualSuspects

Screen capture shows operation:

============Screen capture Windows 2000 simulated in Win95
C:\WORK>demo2
[Buffy the Vampire Slayer] becomes [Buffy the Chosen One]

C:\WORK>
============End screen capture
 
Back
Top