Process Entire Folder using Files As Search And Replace

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Grimus
Posts: 1
Joined: 15 Jul 2015 08:04

Process Entire Folder using Files As Search And Replace

#1 Post by Grimus » 15 Jul 2015 08:11

I'd like to batch process an entire folder of .txt files.

I'd like to use "search.txt" ( containing a block of text ) to search every .txt file in the directory and to replace it with the text block contained in "replace.txt".

Does anyone here know how I can do that?

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Process Entire Folder using Files As Search And Replace

#2 Post by foxidrive » 15 Jul 2015 10:46

An example would help us understand the exact requirement.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Process Entire Folder using Files As Search And Replace

#3 Post by dbenham » 15 Jul 2015 11:34

This isn't too difficult using JREPL.BAT - a hybrid batch/JScript text processing utility.

The following assumes:
- All lines in search and replace files are terminated by CarriageReturn and LineFeed
- No lines are longer than 1021 bytes long (disregarding line terminators)
- No lines contain trailing control characters
- No lines contain null byte (0x00)
- Both the search and replace blocks are less than 8kb in length

The following is untested, but I think it should work.

Code: Select all

@echo off
setlocal enableDelayedExpansion

:: Initialize LF and CR to contain linefeed (0x0A) and carriage return (0x0D)
for /f %%C in ('copy /Z "%~f0" nul') do set "CR=%%C"
set ^"LF=^

^" The empty line above is critial - DO NOT REMOVE


:: Load search and replace terms
call :loadFile search.txt search
call :loadFile replace.txt replace


:: Iterate all .txt files in your folder and perform the search and replace
pushd "yourFolder"
for %%F in (*.txt) do call jrepl search replace /v /l /m /f "%%F" /o -

exit /b
 

:loadFile  file  var
set "%~2="
for /f %%N in ('find /c /v "" <%1') do set "cnt=%%N"
<%1 (
  for /l %%N in (1 1 %cnt%) do (
    set "ln="
    set /p "ln="
    set "%~2=!%~2!!ln!!CR!!LF!"
  )
)

You could write a more robust solution with fewer restrictions via custom JScript, or VBScript, or PowerShell, or ...
But attempting to do this with pure batch is extremely difficult and counterproductive.


Dave Benham

Post Reply