Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String substitution (asterisks) in Batch files?

Tags:

batch-file

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?

like image 460
user541686 Avatar asked Dec 12 '22 10:12

user541686


2 Answers

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
like image 119
jeb Avatar answered Feb 12 '23 03:02

jeb


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%
)
like image 30
sorpigal Avatar answered Feb 12 '23 02:02

sorpigal