prz
prz

Reputation: 3

Batch File - Replace Keyword in txt files

i'm trying to make some BAT files that will scan all files with .txt extension, list them, and replace multiple keywords. I don't know what are txt files names.

Here is what i got:

@echo off

setlocal enabledelayedexpansion

set /a counter=1
set "SEARCH_A=KEYWORD1"
set "REPLACE_A=REPLACED1"
set "SEARCH_B=KEYWORD2"
set "REPLACE_B=REPLACED2"
set "newfile=Output.txt"

for /r %%i in (*.txt) do (

echo %%~nxi>> search_result.txt 

set "textfile=%%~nxi"
set "newfile=Output.txt"

(for /f "delims=" %%j in (!textfile!) do (
    set "line=%%j"
    setlocal enabledelayedexpansion
    set "line=!line:%SEARCH_A%=%REPLACE_A%!"
    set "line=!line:%SEARCH_B%=%REPLACE_B%!"
    echo(!line!
    endlocal
))>"%newfile%"

del !textfile!

rename %newfile%  !textfile!  

set /a counter=!counter!+1    


)

endlocal

And it kind of works. I have got two problems:

Please help me. I'm a total noob btw.

Upvotes: 0

Views: 168

Answers (1)

Stephan
Stephan

Reputation: 56180

Enclose all file/foldernames that (may) contain spaces in quotes (better: get used to enclose all file/foldernames in quotes):

(for /f "usebackq delims=" %%j in ("!textfile!") do (

(usebackq is needed to actually process the textfile instead of just the string of it's name)

del "!textfile!"
rename "%newfile%"  "!textfile!" 

for /r %%i in (*.txt) do (: /r says "recursive" (including sub directories). Just skip the /r to process just the current folder without subfolders.

Upvotes: 1

Related Questions