如何在批处理文件中用其他内容替换字符串中的星号?
如果%MyVar:From=To%
为From
,*
的正常扩展似乎不起作用。
即如果我有:
Set MyVar=From
然后这些不起作用:
Echo %MyVar:*=To%
Echo %MyVar:^*=To%
这样做的正确方法是什么?
答案 0 :(得分:7)
像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
答案 1 :(得分:2)
总有一种方式(但不好吃)
@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%
)
答案 2 :(得分:1)
@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
答案 3 :(得分:1)
在Windows XP上测试的变体:
@echo off 1>nul 2>nul 3>nul 4>nul
set string=**hello*World**
set old_char=*
set new_char=#
pushd %Temp%.\
set string>f1.t
copy nul+nul f0.t
for /f %%a in (f0.t) do (
(
echo 1r%old_char%%%a%new_char%
echo w
echo e
) | edlin /b f1.t
)
for /f "tokens=*" %%i in (f1.t) do set %%i
echo %string% >con
del f0.t f1.t f1.bak
popd
pause
答案 4 :(得分:1)
@Mehrdad:edlin在xp中可用:
hh.exe ntcmds.chm::/edlin.htm
hh.exe ntcmds.chm::/edlin_subcmds.htm
另一种变体:
@echo off
setlocal EnableDelayedExpansion
set string=**hello * World**
set old_char=*
set new_char=#
set new_str=
for /l %%a in (0 1 0xFF) do (
if !string:~%%a^,1!. neq %old_char%. (
set "new_str=!new_str!!string:~%%a,1!"
) else if !string:~%%a^,1!. neq . (
Set new_str=!new_str!%new_char%))
echo !new_str!
pause
答案 5 :(得分:1)
另一:
@echo off
set str=**hello ** world**
set old=\*
set new=#
for /f "useback delims=" %%_ in (`@mshta "about:<script>var string='%str%';new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(string.replace(/%Old%/g,'%New%'));close();</script>" ^|more`) do set res=%%_
echo %str%
echo %res%
pause
答案 6 :(得分:0)
<强> PS + BATCH 强>
@echo off
set string=*hello***lop*
set oldchar=*
set newchar=$
for /f "tokens=*" %%* in ('
"powershell -c ""$env:string"".replace('%oldchar%','%newchar%')"
') do set result=%%*
echo %result%
pause
goto :eof