Thursday, December 06, 2007

Run find/replace/search on multiple files and subdirectories using Vim

Source: http://vim.sourceforge.net/tips/tip.php?tip_id=373

I wanted to recursively edit all html files in a folder/subfolders and run a search and replace command (substitute) in each one, then save the files when finished.

Vim 6.1.255

This is what my batch (WinXP) file does:
Note, since this is running in a windows batch/command file, I had to
escape the % sign.

First start a new instance of gvim, so it doesn't use one that I am already using.  
Give it a specific name so the commands are contained to it.
start gvim --servername BEAD

Using the FOR statement recursively edit all htm files and send them to the gvim session I just started:
FOR /R %%i IN (*.htm) DO gvim --servername BEAD --remote-silent "%%i"

Now, send the bufo command to that server that will run a substitute command.  
Note, I had to double up the % signs since I am in a batch/cmd file.
I also used the ge options so that no error was reported if the search string was not found.
gvim --servername BEAD --remote-send "<ESC>:bufdo %%s/Tweety Bird/Road
Runner/ge<CR>"

Now save all files and exit
gvim --servername BEAD --remote-send "<ESC>:xall<CR>"


Complete batch/cmd file (minus the ***'s)
***********************
start gvim --servername BEAD
FOR /R %%i IN (*.htm) DO gvim --servername BEAD --remote-silent "%%i"
gvim --servername BEAD --remote-send "<ESC>:bufdo %%s/Tweety Bird/Road
Runner/ge<CR>"
gvim --servername BEAD --remote-send "<ESC>:bufdo
%%s/\(^File:.*JPG\).*/\1/ge<CR>"
rem Write all files and exit
gvim --servername BEAD --remote-send "<ESC>:xall<CR>"
***********************


Looking for last minute shopping deals? Find them fast with Yahoo! Search.

0 Comments: