0

我想替换路径字符串中第一次出现的特定字符串,而不是全部出现。

例如:

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

提前致谢。

4

1 回答 1

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
于 2012-11-27T09:26:08.493 回答