Search and replace in Vim across all the project files

The other big option here is simply not to use vim:

sed -i 's/pattern/replacement/' <files>

or if you have some way of generating a list of files, perhaps something like this:

find . -name *.cpp | xargs sed -i 's/pattern/replacement/'
grep -rl 'pattern1' | xargs sed -i 's/pattern2/replacement/'

and so on!


EDIT: Use cfdo command instead of cdo to significantly reduce the amount of commands that will be run to accomplish this (because cdo runs commands on each element while cfdo runs commands on each file)

Thanks to the recently added cdo command, you can now do this in two simple commands using whatever grep tool you have installed. No extra plugins required!:

1. :grep <search term>
2. :cdo %s/<search term>/<replace term>/gc
3. (If you want to save the changes in all files) :cdo update

(cdo executes the given command to each term in the quickfix list, which your grep command populates.)

(Remove the c at the end of the 2nd command if you want to replace each search term without confirming each time)


I've decided to use ack and Perl to solve this problem in order to take advantage of the more powerful full Perl regular expressions rather than the GNU subset.

ack -l 'pattern' | xargs perl -pi -E 's/pattern/replacement/g'

Explanation

ack

ack is an awesome command line tool that is a mix of grep, find, and full Perl regular expressions (not just the GNU subset). Its written in pure Perl, its fast, it has syntax highlighting, works on Windows and its friendlier to programmers than the traditional command line tools. Install it on Ubuntu with sudo apt-get install ack-grep.

xargs

Xargs is an old unix command line tool. It reads items from standard input and executes the command specified followed by the items read for standard input. So basically the list of files generated by ack are being appended to the end of the perl -pi -E 's/pattern/replacemnt/g' command.

perl -pi

Perl is a programming language. The -p option causes Perl to create a loop around your program which iterates over filename arguments. The -i option causes Perl to edit the file in place. You can modify this to create backups. The -E option causes Perl to execute the one line of code specified as the program. In our case the program is just a Perl regex substitution. For more information on Perl command line options perldoc perlrun. For more information on Perl see http://www.perl.org/.