Quick automation in Vim with macros

A macro lets you record a sequence of commands to a registry.

q<letter><commands>q

The macro can be replayed with the following command (once by default).

<number>@<letter>

You can view the macro using the reg command.

:reg <letter>

Finally, these commands will edit the macro in a new buffer.

:new
:put <letter>
(make modifications to the macro)
:"<letter>yy

Example

Consider the following file.

192.0.2.10
192.0.2.20
198.51.100.3
203.0.113.7
203.0.113.66

Suppose we want to move each IP to the same comma-separated line.

192.0.2.10,192.0.2.20,198.51.100.3,203.0.113.7,203.0.113.66

This can be achieved with a macro. The following command records the key sequence ggjI<BS>,<ESC> to the registry “a“.

qaggjI<BS>,<ESC>q

The macro can be replayed to the remaining lines in the file with the <number>@<letter> command.

5@a

I find this to be a handy way to do some quick automation in Vim.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *