How to quickly search and replace in multiple files using Vim and some ruby library (gems)

Why I wrote this script?

I am a big fan of automation. This is one of the trick I use quite often when I need to do global search and replace multiple strings for a list of know file types.

After some searching around for the solution, I found none that work the way I really want to do.

In this example I will show you how to use Vim and some of my ruby library to quickly perform search and replace string in a very simple ways.

What do we need?

We will be using the following tools and library

How?

# Make a sample directory we are going to use
mkdir -p ~/codes/

# Clone the example project for use in this case I am going to use `github_copier` my original gem

git clone git@github.com:agilecreativity/github_copier.git

# Change to this directory
cd ~/codes/github_copier
# Install the first gem
gem install code_lister

# Install the second gem
gem install extension_lister

# If you are using rbenv, type this to refresh the gem list
rbenv rehash
$extension_lister -b .
.gem
.gemspec
.lock
.md
.rb

Let’s say that we only care about these extension .gemspec, .md, and .rb and we want to skip .gem or .lock file.

In addition we like to search and replace the following files LICENSE,Rakefile,Guardfile,github_copier that have no extension.

$code_lister -b . -e rb,md,gemspec -f LICENSE,Rakefile,Guardfile,github_copier
./CHANGELOG.md
./Guardfile
./LICENSE
./README.md
./Rakefile
./bin/github_copier
./github_copier.gemspec
./lib/github_copier
./lib/github_copier.rb
./lib/github_copier/filename_cleaner.rb
./lib/github_copier/github_copier.rb
./lib/github_copier/opt_parser.rb
./lib/github_copier/version.rb
./test/lib/github_copier
./test/lib/github_copier/test_github_copier.rb
./test/test_helper.rb

Now we are good to go to the next step

Create the new file called search-and-replace.vim with the following content:

:silent! argdo %s/github_copier/github_cloner/ge | update | %s#GithubCopier#GithubCloner#ge | update | wq

The script above will help us perform search and replace github_copier with github_cloner and GithubCopier with GithubCloner.

As a note we can add more term to this list by adding them between argdo and | wq like:

.../ge |update | %s/search_for/replace_term/ge | update | ... | wq
vim `code_lister -b . -e rb,md,gemspec -f LICENSE,Rakefile,Guardfile,github_copier -r` -s ./search-and-replace.vim

And that’s it. The two terms should be properly replaced in the list of files we specified.

Happy Hacking!

comments powered by Disqus