Monday, October 15, 2012

VIM Tips: Multiple Commands

This tip may be too simple and not not the best way to do it. However, it saves my tremendous time. Last week, I was going to bring my Visual Studio solution to my work. This solution contains a lots of projects. I realized that there are some namespaces and copy right issues to be updated. I could use VS to do it. But the VS at work is a new one, without tools like Refactory tool, CodRush Express, Resharper.

I did not like the native Find & Replace in VS. I decided to use VIM to do the job. The challenge I faced was that, first, I had to find all the files contains the strings I would like to replace, and secondly, do the find and replace for each file.

I used TotalCommander tool to do the search. It has built-in find feature and it is very powerful. I can easily get the search result files in one panel. Then I added a tool bar associated with VIM (set parameter %P%N). It is a very cool tool.

Next, I tried to use VIM to do replacement manually. I had too many .cs files. It was just to tedious. Then I searched for a way to do replacement, then save the changes and quit. Can I do three commands in one line? Soon I found a way to do it:

:%s/searchpattern/replacement/g | write | q

In VIM the pipe char is used to link a list of commands. This made my job much quicker. Afterward, I found that this could be done on command line like this:

gvim -c "%s/searchpattern/replacement/g | write | q" test.cs

I think that there must be a better way to run a chained command in a Windows command console: first finding all the files containing expected strings, and next using gvim to do the replacement.