我想替换路径字符串中第一次出现的特定字符串并非全部出现。
例如:
set strpath=D:\Temp\Test\projects\Test
set strreplace=Test
set strpath=%strpath:%strreplace%=MyProjects%
echo strpath = %strpath%
但它取代了所有的事件 strpath = D:\ Temp \ MyProjects \ projects \ MyProjects
我需要像
这样的输出 D:\Temp\MyProjects\projects\Test
提前致谢。
答案 0 :(得分:0)
我为你的问题做了一个功能:
@Echo OFF
SETLOCAL Enabledelayedexpansion
:: By Elektro H@cker
set "strpath=D:\Temp\Test\projects\Test"
REM Call :REPLACE_FIRST "Variable" "word" "to replace word"
Call :REPLACE_FIRST "%strpath%" "Test" "Anything"
Echo %replaced_str%
Pause&Exit
:REPLACE_FIRST
Set "str=%~1"
Set "word_before=%~2"
Set "word_after=%~3"
Set "splited_str=%str:\= \ %"
FOR %%# in (%splited_str%) do (
IF "%%#" EQU "!word_before!" (
Set "replaced_str=!replaced_str!!word_after!"
Set "word_before="
) ELSE (
Set "replaced_str=!replaced_str!%%#"
)
)
GOTO:EOF
输出:
D:\Temp\Anything\projects\Test