tomato
tomato

Reputation: 841

Feed in a list of find and replace values with batch

I'm looking for a way to find and replace multiple words in a text file using a Windows batch script.

I know replacing a word can be done so with this bat script:

@echo off &setlocal
set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"
del %textfile%
rename %newfile%  %textfile%

Now, I just have to take it one step further and feed in the search and replace strings from another file similar to this format:

search_string1, replace_string1
search_string2, replace_string2
search_string3, replace_string3
.
.
.

I would think that I would somehow process the file line by line, and parse them into two variables (search, replace) and then feed that into the script above. Any thoughts? I'm new to Windows batch scripts and have never really made one before so mind my newbie questions.

Upvotes: 3

Views: 4019

Answers (1)

Aacini
Aacini

Reputation: 67216

This type of text replacements are slow and prone to fail when performed via a Batch file. I wrote FindRepl.bat program that is a Batch-JScript hybrid script that not only run much faster and with no errors, but it also allows to perform the multiple replacements you are looking for in just one processing pass of the data file. JScript is a programming language that is included in all Windows versions from XP on. Using FindRepl.bat program you may solve your problem this way:

@echo off
setlocal EnableDelayedExpansion
set "search="
set "replace="
for /F "tokens=1,2 delims=," %%a in (replacements.txt) do (
   set "search=!search!|%%a"
   set "replace=!replace!|%%b"
)
set "search=!search:~1!"
set "replace=!replace:~1!"
< Input.txt FindRepl =search /A =replace > Output.txt

Note that all text placed after the comma in the replacements file is the replacement string, including spaces.

You may download FindRepl.bat program from this site. Place it in the same folder of previous program or, better yet, in a folder included in %PATH%, so you may use it directly.

Upvotes: 1

Related Questions