Page 1 of 1

updated function :substitute

Posted: 26 Jul 2024 13:34
by Gustaaf
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