How to search and replace multiple files with Vim

Here are the steps that I use to rename the project from

github_exporter to code2pdf

For this I use my very own code_lister gem which similar to using find | grep command but provide more flexibility to list only specific list of files.

e.g. we need to work with the following file:

# files with extension
# => *.rb, *.md, *.gemspec

# files without extension
# => Gemfile, Rakefile, bin/github_exporter

So to get the list I first run the following command:

# Install the gem that work similar to Unix `find` command
$gem install code_lister

# Change to the correct directory
$cd ~/codes/bitbucket/rubygems/github_exporter/

# Get the list of files
$code_lister --base-dir . \
             --exts rb gemspec md \
             --non-exts Gemfile Rakefile github_exporter

The file list will be something like

./CHANGELOG.md
./Gemfile
./README.md
./Rakefile
./bin/github_exporter
./github_exporter.gemspec
./lib/github_exporter
./lib/github_exporter.rb
./lib/github_exporter/cli.rb
./lib/github_exporter/exporter.rb
./lib/github_exporter/github_exporter.rb
./lib/github_exporter/logger.rb
./lib/github_exporter/version.rb
./test/lib/github_exporter
./test/lib/github_exporter/test_github_exporter.rb
./test/test_helper.rb
# Note: that the backtick '`' is used to
$vim  `code_lister --base-dir . \
                   --exts rb gemspec md \
                   --non-exts Gemfile Rakefile github_exporter`

The commands that I used are:

from inside Vim, you can see that our arguments should be populated:

" replace 'github_exporter' with 'code2pdf'
:argdo %s/github_exporter/code2pdf/gce | update

" replace 'GithubExporter' with 'Code2Pdf'
:argdo %s/GithubExporter/Code2Pdf/gce | update

You will get the prompt for confirmation if you like to rename the text

e.g. rename any file containing the word ‘github_exporter’ to ‘code2pdf’

$find . -type f -iname "github_exporter" | grep -v \.gem$

Automate using the vim script

Here is how to automate this using the combination of VimScript/Shell script.

" Note: the \C make the case sensitive subsitution (ignore the setting in ~/.vimrc)
:argdo %s/\Cgithub2epub/code2epub/ge | update | %s\CGithub2Epub/Code2Epub/gc | update | wq
$vim `code_lister -b . -e rb md gemspec -f github2epub Gemfile Rakefile` -s command.vim

Useful Links

comments powered by Disqus