updated function :substitute

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Gustaaf
Posts: 6
Joined: 07 May 2019 04:04

updated function :substitute

#1 Post by Gustaaf » 26 Jul 2024 13:34

The substitute function seemed a bit slow too me. Also added optional OutFile parameter.

I have updated it, or it can get its own name :searchandreplace.

Code: Select all

:substitute OldStr NewStr File [OutFile] -- substitutes a string in a text file
::                                     -- OldStr [in]  - string to be replaced
::                                     -- NewStr [in]  - string to replace with
::                                     -- File   [in]  - input file to be parsed
::                                     -- OutFile [in] - (optional) output file for modified content
:$created 20060101 :$changed 20101122 :$changed 20240726 :$categories FileManipulation
:$source https://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
SET "outputFile=%~4"
IF "%outputFile%"=="" SET "outputFile=%~3"
SET "tempFile=%TEMP%\tempFile.txt"
(
    FOR /F "tokens=1,* delims=]" %%A IN ('"type %~3 | find /n /v """') DO (
        SET "line=%%B"
        IF DEFINED line (
            SET "line=!line:%~1=%~2!"
            ECHO(!line!
        ) ELSE (
            ECHO.
        )
    )
) > "%tempFile%"
MOVE /Y "%tempFile%" "%outputFile%"
ENDLOCAL
EXIT /B
REM Example usage of the function
CALL :substitute "oldtext" "newtext" "input.txt" "output.txt"
CALL :substitute "oldtext" "newtext" "input.txt" REM This will replace the input file content

Post Reply