How do I use a batch file to recursively replace a string in files?
Yuck, blindly doing wholesale substitution like that on an entire directory tree structure would make me nervous. But if you think it is safe...
It is potentially tricky do do what you want using pure batch, depending on your file content. But it is easy to do with a hybrid JScript/batch utility I wrote called REPL.BAT. The utility performs regex search and replace on stdin, and writes the result to stdout. It is pure script that runs on any modern Windows machine from XP forward, so it does not require installation of any 3rd party .exe
file. The REPL.BAT utility and documentation is available here..
Assuming you have REPL.BAT in your current directory, or better yet, somewhere within your PATH, then the following simple one liner should do the trick directly from the command line, no batch required.
for /r %F in (*.sql) do @(type "%F"|repl "C:\" "E:\" >"%F.new"&move /y "%F.new" "%F" L >nul)
You can make the search case insensitive by adding the I
switch.
for /r %F in (*.sql) do @(type "%F"|repl "C:\" "E:\" I >"%F.new"&move /y "%F.new" "%F" L >nul)
Or if you prefer a batch script (with I
switch)
@echo off
for /r %%F in (*.sql) do (
type "%%F"|repl "C:\" "E:\" LI >"%%F.new"
move /y "%%F.new" "%%F" >nul
)
I used the L
literal switch throughout; the other option is to escape the \
instead.
repl "C:\\" "E:\\" I