Replace in Multiple Files - the Vim Way

Search and Replace in multiple files

Replacing text in multiple files is really easy with Vim. However, it’s not quite popular feature and a lot of people don’t know that such exists. In this post we will show you a few tricks that will get the job done.

If you want to replace _params with params in the current buffer, you can do it by executing the following command:

1
:%s/_params/params/ge

However, if the substitution has to be made across all files with extension .rb in a directory, you will have to use argdo:

1
2
:args app/controllers/*.rb
:argdo :%s/_params/params/ge | update

Also you can put the c flag, which will ask for confirmation before each change. Pretty neat, huh?

The limitation of argdo is that it won’t search the supplied directory recursively, but you can use the awesome DirDo.vim plugin to accomplish it:

1
2
3
:DDD app/controllers
:DDP *.rb
:DDO :%s/_params/params/ge | update

Finally, the unix tools sed and awk are always an option that you might consider handy.

About the author

Veselin Todorov is a software consultant focused on testing, code quality and building awesome products. He is helping companies to ship their products with confidence and style.

If you are passionate about JavaScript, Node.js, TDD, building and growing applications, you should visit his blog at RobustJS.com