Text

Vim Macros - A practical example

I have been using Vim for the last eight months in a daily basis and the more I use it the more I like it. There was some functionality that always seemed like dark to me and I never understood how to use it: Vim Macros. So today I finally learned how to use it and it was really useful. I decided to share my humble enlightenment and in this blog post you will read my findings. Suppose you have very big file with some sort of format that you want to change:
"san francisco", "(californaia)" => "usa"
"san antonio",  "(californaia)" => "usa"
"new york", "(new york)" => "usa"
"seattle", "(washigton)" => "usa"
...
And you would like to change that file to something like this:
'san francisco', 'californaia',  'usa'
'san antonio',  'californaia' , 'usa'
'new york', 'new york' , 'usa'
'seattle', 'washigton', 'usa'

How would you do that? If you are a regular expression magician, maybe you could find one really quickly that will solve your problem. But if you are like me, you wouldn’t like to spend 10-15 minutes figuring out what is the regular expression that is going to solve your problem.

Vim macros are here to save us. In vim, a macro is a sequence of commands that are save for future uses. To start recording a macro you type ‘q’ followed by a letter (called register), to store the macro . Then type the sequences of commands and then ‘q’ again to stop recording.

After that if you want to use the macro, you type ‘@’ followed by the register where the macro is stored. Let’s see this with our text what would the macro look like:

qa0r'ESCf"r'ESCf"r'ESClxESCf)xr'lr,lxxlr'f"r'ESCq
ESC stands for the key “ESCAPE”. So after that we have in register a our macro that transform our line in the desired format. So now we need just to apply that macro in the whole file. Type the following in command mode:
2,158norm! @a

Et voila! Your file is now the way you want it. I know it looks a little bit long the lists of commands that you have to type to transform the text, but if you are familiarized with vim, is something that you would have done anyway. The difference is that you recorded the sequence of commands and now you could repeat it over and over.

NOTE: If you have plugins like vim surrounds, the sequence of keystrokes would have been shorter. However, for the example I just used plain vim commands.

April 03, 2012
0 comments
Posted by rafaelchacon
∞ Short URL
");pageTracker._trackPageview()}catch(err){}
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.