DOS Batch – Find and Replace all occurrences of a string with another string

code

A fantastic write-up for a batch file, DOS Batch – Find and Replace, that allows string substitution in a text file. It parses each line of a text file for a particular string and replaces it with another string. For example, to replace all occurrences of “red” in “color.txt” with “blue” and put the output on the screen. The script is called BatchSubstitute.bat.

BatchSubstitute.bat (original script)

@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude - parses a File line by line and replaces a substring"
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
:$changed 20100115
:$source http://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo

To direct the output the screen, which is the default design, the following two possibilities exist.

BatchSubstitute.bat oldstring newstring filename.txt
type filename.txt|BatchSubstitute.bat oldstring newstring

The way that it is written requires piping the output or a redirect to a new file.

BatchSubstitute.bat oldstring newstring filename.txt>newfile.txt
type color.txt|BatchSubstitute.bat oldstring newstring>newfile.txt

BatchSubstitute.bat (updated script)

@echo off

REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

if /I "%~1"=="/h" goto:help
if "%3"=="" goto:help

if "%~1"=="" findstr "^::" "%~f0"&goto:help
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""')  do %%~X >> %3_new
    ) ELSE echo.
)
move /Y %3_new %3 >nul

goto:eof

:help
echo BatchSubstitude - parses a File line by line and replaces a substring
echo.
echo Usage: %0 [oldstr] [newstr] [filename]
echo.          oldstr  - string to be replaced
echo.          newstr  - string to replace with
echo.          filname - file to be parsed
echo.
goto:eof

:eof

However, a little tweaking to the code will no longer require piping or output redirects. The syntax is much simpler, the original file will be overwritten with the new strings.

BatchSubstitute.bat oldstring newstring filename.txt

A special note from the original article. There are known restrictions that apply. Lines starting with “]” character will end up empty, oldstrinr must not start with “*”, and lines must not contain any of the following characters within a quoted string: “&<>|^”,