如何将字符串中的星号替换为其他批处理文件中的星号?
如果%MyVar:From=To%
是*
,则From
的正常扩展似乎不起作用。
也就是说,如果我有:
Set MyVar=From
那么这些就没用了:
Echo %MyVar:*=To%
Echo %MyVar:^*=To%
正确的方法是什么?
发布于 2011-08-12 05:12:41
这是一个类似Sorpigal的解决方案,但它也处理以星星和多颗恒星开始的文本,并且它不会以引号失败。
@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
发布于 2011-08-11 11:16:59
总有一种方法(无论多么令人不快)
@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%
)
发布于 2011-08-12 11:00:30
@echo off
setlocal EnableDelayedExpansion
set old_str=**hello * world **
set oldchar=*
set newchar=$
set new_str=
>$1 (<nul,set/P=%old_str%)
For %%a in ($1) do set /A cnt=%%~za
>$2 (For /l %%a in (1 1 %cnt%) do <nul,set/P=µ)
For /f "tokens=3" %%a in ('"fc /b $2 $1|findstr :"') do (
set /A dec=0x%%a
%ComsPec% /c exit /b !dec!
if "!=ExitCodeAscii!"=="%oldchar%" (
set new_str=!new_str!%newchar%
) else (
set new_str=!new_str!!=ExitCodeAscii!
)
)
del $?
echo %old_str%
echo %new_str%
pause
https://stackoverflow.com/questions/7022640
复制相似问题