Search code examples
batch-filefindstr

Batch find text in file and replace with other text


I need to use Batch to check file Directory.twml to see if it contains any words from file blocked.twml and if it does replace with [Blocked]

Here is an example of both files:

Directory.twml

11:38:38.90 [System] Twml Has joined the chat.
11:38:41.17 [User]   Twml says: line one
11:38:42.96 [User]   Twml says: line bad two
11:38:46.27 [User]   Twml says: line three
11:38:50.16 [User]   Twml says: you get the idea here
11:38:52.35 [System] Twml Has logged off.

Blocked.twml

word1
word2
word3
bad
word5
word6

What i want Directory.twml to say look like is

11:38:38.90 [System] Twml Has joined the chat.
11:38:41.17 [User]   Twml says: line one
11:38:42.96 [User]   Twml says: line [Blocked] two
11:38:46.27 [User]   Twml says: line three
11:38:50.16 [User]   Twml says: you get the idea here
11:38:52.35 [System] Twml Has logged off.

I already can use Findstr to look in the file and see if the text exists but thats as far as i can get, I need to not check for a set word but check the list of words in the file Blocked.twml

findstr /i "bad" <"Directory.twml" 1>nul

Also i can remove the word from the file but i want to replace it not just remove

findstr /i /v /c:"%text%" Directory.twml > "Directory.twmll" 2>nul 
del Directory.twml /s /a >nul
copy Directory.twmll Directory.twml >nul
attrib +h Directory.twml
del Directory.twmll /s /a >nul

But again this is a set text to look for not from what is in a file as a list

If Directory.twml contains anything in Blocked.twml replace with [Blocked] but i cant figure out how to do it

========= Edit ===========

This is the solution:

(
for /f "delims=" %%A in (Directory.twml) do (
set "line=%%A"
for /f "delims=" %%B in (blocked.twml) do set "line=!line: %%B = [Blocked] !"
echo !line!
)
)>Directory.new

Its output looked like this for me

13:22:14.16 [User]   twml says: this is a test
13:22:20.37 [User]   twml says: this is a [Blocked] word test

Solution

  • Read Directory.twml line by line. For each line, read blocked.twml and replace each word with the string [Blocked]. Echo the changed line. Redirect the whole output to a new file:

    @echo off 
    SETLOCAL ENABLEDELAYEDEXPANSION
    (
      for /f "delims=" %%A in (Directory.twml) do (
        set "line=%%A"
        for /f "delims=" %%B in (blocked.twml) do set "line=!line:%%B=[Blocked]!"
        echo !line!
      )
    )>Directory.new
    

    I'll leave it to you to rename the new file to the original name.

    Note: something like abadad will be changed to a[Blocked]ad. You could change set "line=!line:%%B=[Blocked]!" to set "line=!line: %%B = [Blocked] !" to catch word boundaries, but then This is bad, I think. wouldn't be changed.

    Note: a single! will be removed. If there are more than one ! in a line, text between them will disappear. Batch isn't really a good choice to do such things...