Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading