devroom.io/content/posts/2012-06-18-search-and-replace-in-multiple-files-with-vim.md

57 lines
1.8 KiB
Markdown
Raw Normal View History

2017-03-20 15:35:19 +00:00
+++
date = "2012-06-18"
title = "Search and Replace in multiple files with Vim"
tags = ["Rails", "vim"]
slug = "search-and-replace-in-multiple-files-with-vim"
+++
2015-03-26 11:28:08 +00:00
2017-03-20 15:35:19 +00:00
I recently learned a nice VimTrick™ when pairing with [Arjan](http://arjanvandergaag.nl). We upgrade an app to Rails 3.2.6 and got the following deprecation message:
``` text
DEPRECATION WARNING: :confirm option is deprecated and will be removed from Rails 4.0.
Use ':data => { :confirm => 'Text' }' instead.
```
2015-03-26 11:28:08 +00:00
Well, nothing difficult about that, but we have quite a few `:confirm` in this app.
Firstly we checked where we used them (note we use ruby 1.9 hash syntax everywhere):
2017-03-20 15:35:19 +00:00
``` shell
ack -l "confirm:" app
```
2015-03-26 11:28:08 +00:00
Now you have a listing of all the files that contain the `:confirm` hash key. You can leave out the `-l` option to get some context for each find.
Now, we need to open Vim with those files:
2017-03-20 15:35:19 +00:00
``` shell
ack -l "confirm:" app | xargs -o vim
```
2015-03-26 11:28:08 +00:00
Vim will open the first of these files. Here's a snippet of what you may find:
2017-03-20 15:35:19 +00:00
``` haml
= link_to "Delete", something_path, confirm: "Are you sure?"
```
2015-03-26 11:28:08 +00:00
Now, search and replace is easy:
2017-03-20 15:35:19 +00:00
``` vim
:%s/confirm: ".*"/data: { & }/g
```
2015-03-26 11:28:08 +00:00
This will surround the current confirm with the `data` hash. Just the way Rails likes it. The `&` character will be replaced with whatever text matched the search pattern.
You could repeat this for every file manually. But, you're using Vim.
2017-03-20 15:35:19 +00:00
``` vim
:argdo %s/confirm: ".*"/data: { & }/g | update
```
2015-03-26 11:28:08 +00:00
This will perform the search and replace on each of the supplied arguments (in this case the files selected with `ack`) and update (e.g. save) those files.
Now you can quit Vim and enjoy the glory of all the disappearing deprecation warnings.
2017-03-20 15:35:19 +00:00
Note: to do this with the ruby 1.8 hash syntax, just update the search and replace texts accordingly.