Replace a substring with the contents of a variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
cocoabsb
Posts: 2
Joined: 31 May 2013 17:36

Replace a substring with the contents of a variable

#1 Post by cocoabsb » 31 May 2013 18:00

Hi,

See the following piece of code:

set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%


How can I use variables instead of teh and the in the line "set str=%str:teh=the%" ?

I have tried this:
set str=teh cat in teh hat
echo.%str%
var1=teh
var2=the
set str=%str:%var1%=%var2%%
echo.%str%


but it did not work.

How can this be done?

Thanks

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Replace a substring with the contents of a variable

#2 Post by foxidrive » 31 May 2013 18:16

This should work.

Code: Select all

set str=teh cat in teh hat
echo.%str%
var1=teh
var2=the
call set "str=%%str:%var1%=%var2%%%"
echo.%str%

Aacini
Expert
Posts: 1932
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Replace a substring with the contents of a variable

#3 Post by Aacini » 31 May 2013 18:27

Or this one...

Code: Select all

setlocal EnableDelayedExpansion
set str=teh cat in teh hat
echo.%str%
var1=teh
var2=the
set str=!str:%var1%=%var2%!
echo.%str%

cocoabsb
Posts: 2
Joined: 31 May 2013 17:36

Re: Replace a substring with the contents of a variable

#4 Post by cocoabsb » 31 May 2013 20:36

Thanks a lot. Both worked.

Post Reply