How do I replace an asterisk in a string with something else, in a batch file?
The normal expansion of %MyVar:From=To%
doesn't seem to work if From
is *
.
i.e., if I have:
Set MyVar=From
then these don't work:
Echo %MyVar:*=To%
Echo %MyVar:^*=To%
What's the correct way to do this?
A solution like the one of Sorpigal, but this handles also text beginning with stars and multiple stars to replace, and it doesn't fail with quotes.
@echo off
setlocal EnableDelayedExpansion
rem replace all "*" with "."
set "replace=."
set "var=*One**two***three"
rem Add dummy char to accept also a star in front
set "var=#!var!"
:replaceLoop
for /F "tokens=1 delims=*" %%A in ("!var!") do (
set "prefix=%%A"
set "rest=!var:*%%A=!"
if defined rest (
set "rest=!REPLACE!!rest:~1!"
set Again=1
) else set "Again="
set "var=%%A!rest!"
)
if defined again goto :replaceLoop
set "var=!var:~1!"
echo !var!
exit /b
There's always a way (however unpalatable)
@echo off
set myvar=one two * four
set replacement=three
for /f "tokens=1,2 delims=*" %%a in ("%myvar%") do (
set tmp1=%%a
set tmp2=%%b
echo %tmp1%%replacement%%tmp2%
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With