use variable substitution in windows batch

Microsoft Windows 7 home premium 64-bit
January 18, 2011 at 19:49:26
Specs: Windows 7, 4/16
How can replace certain characters by using variables as suppose to actual values?

I used the syntax %variable:StrToFind=NewStr%. Not sure if I should try something else. It works if I dont use variables and just replace it with actual values.

set strToFind=This
set var=TestThisMachine
set newstr=My
:: Note: the results should be TestMyMachine
:: i tried these 2 that I thought might work

set results=%var:%strToFind%=%newstr%%

:: and this one
setlocal enabledelayedexpansion
set results=%var:!strToFind!=!newstr!%

Please tell what I'm doing wrong. Thank you.

See More: use variable substitution in windows batch

Report •

January 18, 2011 at 21:06:18
setlocal enabledelayedexpansion
set results=!var:%strToFind%=%newstr%!

A few notes:

1. This method doesn't work if you want to replace a string that contains "=" (the replacement can contain "=")

2. Delayed expansion is problematic when strings contain ! - it tries to expand them....

Report •

January 19, 2011 at 06:49:09
Thank you Judago. It worked perfectly.

Report •
Related Solutions

Ask Question