Use macros in VIM – a example

This is a very nice function in VIM. The ability to record your actions and play them back one or hundreds of times. Perfect for doing boring time consuming and repetitive tasks in text files.

Here is a problem that I solved using macro recording in VIM:

I had a list of 233 customer numbers from a database in a file like this:

0000003173
0000003064
0000003084
0000003540
0000003539
0000003140
0000003089
...

Now I had to use these numbers in a SQL expression. Problem was that the numbers actually were text strings. Going thru 233 rows adding ‘ to each side of the number plus a comma after each row would take quite some time and I would be very boring. So here is what I did:

I opened the the file in VIM.

Start recording

Esc  #switch to command mode
q    #start recording
a    #name macro 'a' - you can choose any low case letter here

This will start the recording process and place the text recording on the last line of the window

Now I pressed ‘i’ for Insert Mode (– – INSERT – – recording)

Then I simply added a before and after the topmost number and ended with a , (comma) so it looked like this:

'0000003173',
0000003064
0000003084
0000003540
0000003539
0000003140
0000003089
...

I then placed the cursor infront of the second number, pressed ESC (to exit INSERT mode) and then‘q’ to stop the recording (the word ‘recording’ disappears)

Now to run this on the rest of the 232 numbers you just write (in command mode):

232@a # This runs the macro named 'a' 232 times

If you one want to run it once just write ‘@a’ – the number before is how many times you want to run the macro

After this I ended up with a file looking like this

'0000003173',
'0000003064',
'0000003084',
'0000003540',
'0000003539',
'0000003140',
'0000003089',
...

Very smooth indeed 🙂

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>