Page 1 of 1

text replace in multiple files using a list file

Posted: 17 Sep 2011 09:07
by SXGuy
i currently have a batch file which copies a base file multiple times and renames each copy with a list of words given inside a list file.

Code: Select all

SET source_file=index.php
SET name_list_file=filenames.txt

FOR /F "usebackq delims=," %%G IN (`TYPE %name_list_file%`) DO (
    COPY %source_file% %%G
)


However, i need to expland this batch process by replacing a given word inside each new file with the same word stored in the list file.

the given word to replace can be stored inside the batch command for example SET rename="Word"

Any help would be really apreciated.

Thank you.

Re: text replace in multiple files using a list file

Posted: 17 Sep 2011 21:24
by dbenham
Probably best if you download a free utility like sed for Windows.

Windows batch is pretty lousy at processing text files. But if you want to use pure batch without a utility like sed, it can be done.

Option 1 (untested)
I think this is the fastest pure batch option. It should work as long as the source file lines are terminated with <CR><LF> (Windows style) and not simply <LF> (Unix style)

Code: Select all

@echo off
setlocal enableDelayedExpansion

set source_file="index.php"
set name_list_file="filenames.txt"
set "rename=word"

for /f %%n in ('type %source_file%^|find /c /v ""') do set len=%%n
for /f "usebackq delims=," %%G in (%name_list_file%) do <%source_file% (
  for /l %%l in (1 1 %len%) do (
    set "line="
    set /p "line="
    if defined line (
      echo(!line:%rename%=%%G!
    ) else echo(
  )
)>%%G


Option 2 (untested)
This is slower, especially if the source file is large. But it should work with both Windows and Unix style lines.

Code: Select all

@echo off
setlocal disableDelayedExpansion

set source_file="index.php"
set name_list_file="filenames.txt"
set "rename=word"

for /f "usebackq delims=," %%G in (%name_list_file%) do (
  for /f "tokens=*" %%a in ('find /n /v "" %source_file%') do (
    set "line=%%a"
    setlocal enableDelayedExpansion
    set line=!line:*]=!
    if defined line (
      echo(!line:%rename%=%%G!
    ) else echo(
    endlocal
  )
)>%%G


Dave Benham

Re: text replace in multiple files using a list file

Posted: 18 Sep 2011 02:30
by SXGuy
Thanks for your reply.

The first example works perfectly!

Thank you :)