Edit: To answer the clarified question:
If you can ensure that original
is always the same, and is only in the path once, use:
@Echo Off
Set "Find=original"
Set "Replace=replaced"
Set "OldPath=%~1"
Call Set "NewPath=%%OldPath:\%Find%\=\%Replace%\%%"
Echo %NewPath%
This will replace the first instance of \original\
with \replaced\
. Testing:
C:\> ChangePath.bat "Alice\original\Clive"
Alice\replaced\Clive
C:\> ChangePath.bat "Alice\original\Clive\Denver"
Alice\replaced\Clive\Denver
C:\> ChangePath.bat "Alice\Bob\original\Clive"
Alice\Bob\replaced\Clive
Previous answer
To change the second section of the path, you can use:
@Echo Off
Set "Replace=Replacement Path"
Set "PathABC=%~1"
Set "PathBC=%PathABC:*\=%"
Call Set "PathA=%%PathABC:\%PathBC%=%%"
Set "PathC=%PathBC:*\=%"
Set "NewPath=%PathA%\%Replace%\%PathC%"
Echo %NewPath%
Testing:
C:\> ChangePath.bat "Alice\Bob\Clive"
Alice\Replacement Path\Clive
This relies on there being no leading slash. It replaces the text between the first and second slash.
Edit: To explain what %%
means.
%%
is a method to escape the percentage sign. If I wrote the following line it would treat % Green 50%
as a variable. Since that variable is undefined, it will write the following output.
C:\> Echo Red 90% Green 50% Blue 5%
Red 90 Blue 5%
What I need to write is:
C:\> Echo Red 90%% Green 50%% Blue 5%%
Red 90% Green 50% Blue 5%
The following line goes through a few transformations. Here is each step of its transformation.
:: Original line
Call Set "NewPath=%%OldPath:\%Find%\=\%Replace%\%%"
:: The variables encased in single `%` are evaluated:
Call Set "NewPath=%%OldPath:\original\=\replaced\%%"
:: `Call` runs the rest of the line as a command. The `%%` are evaluated to `%`.
Set "NewPath=%OldPath:\original\=\replaced\%"
:: The search and replace on `OldPath` occurs.
Set "NewPath=Alice\replaced\Clive"
:: The final command is processed.