Shell – How to do a find-replace on a windows batch file string

batchpowershell

I want to change a variable from some\original\path to some\replaced\path by doing a find-replace and changing the "original" part in the path.

set x=some\original\path
set y= ????
(y is now some\replaced\path)

How would I go about doing this in a Windows batch file? Note that:

  • I want to keep the code flexible so no hardcoding the strings or character indexes
  • I am fine with a Powershell solution too. I'm looking for whatever is the simplest, most mantainable and can run on my Windows 7 machine.

Solution:

In batch files you can do string replacements in the %% interpolation process

set y=%x:original=replaced%

Best Answer

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.
Related Question