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


# 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

# 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 .

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

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