Vim: Find/Replace in projects using ack

Since moving to vim from Sublime Text 2 the one thing I have been less than happy with is find and replace in files. This seems to be the accepted solution:

:args app/views/*/*
:argdo %s/search/replace/ge | update

The problem with this way though is that it’s adding a bunch of files that don’t need to be searched and taking up a lot more memory than it needs to. This also loads folders and files which cause errors when vim tries to parse them. After a lot of experimentation I’ve come up with a better solution. Using ack I only add the files that contain the search parameters which saves a lot of ram.

:args `ack -l keywords`
:argdo %s/keywords/replacement/ge | update

This works great but is still a lot of typing so after messing around with it a bit more I came up with the solution of typing /search/replace/ into whatever file I’m in on a new line and then hitting fr to remove the line and use it to find and replace in files. Here is the section from my .vimrc that deals with find replace.

" Finds and replaces in files based on the the current line.
map <Leader>fr ^l"ayt/^v$h"byu:vsp<CR>:args `ack -l <C-R>a`<CR>:argdo %s<C-R>bge \| update<CR>

" Same as above but asks before all the changes.
map <Leader>far ^l"ayt/^v$h"byu:vsp<CR>:args `ack -l <C-R>a`<CR>:argdo %s<C-R>bgce \| update<CR>

November 30, 2012
vimack


[