Replace mulitple Inputs in txt document using batch file

I am looking for a way to scan a .txt file for mulitple words
and replace them with other words using a batch script.
For example I would like to change two words : {Hello} and {beautiful}

Before:
"Hello stack community what a beautiful day today"

After:
"Hi stack community what a lovely day today"

I found a code that could change one input at the time:

setlocal enabledelayedexpansion
set SEARCHTEXT1=Hello
set REPLACETEXT1=Hi 
set SEARCHTEXT2=beautiful
set REPLACETEXT2=lovely

set OUTPUTLINE=
for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A

SET modified=!string:%SEARCHTEXT1%=%REPLACETEXT1%!
echo !modified! >> %OUTTEXTFILE%
)

This will only change the value "Hello" to "Hi"
I would also like to replace the other words like "beautiful" to "lovely"

>Solution :

@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=input.txt
set OUTTEXTFILE=output.txt

set "SEARCHTEXT1=Hello"
set "REPLACETEXT1=Hi"
set "SEARCHTEXT2=beautiful"
set "REPLACETEXT2=lovely"

(for /f "delims=" %%A in (%INTEXTFILE%) do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT1%=%REPLACETEXT1%!"
    set "modified=!modified:%SEARCHTEXT2%=%REPLACETEXT2%!"
    echo !modified!
)) > %OUTTEXTFILE%

This script will replace both "Hello" and "beautiful" in the input file and write the modified text "Hi" and "Lovely" to the output file. Make sure to adjust the file paths and the replacement text as needed for your specific use case.

Leave a Reply