Skip to content

Vim macros: record an edit once, play it a hundred times

NinjaLesson 54 of 668 min

Record a Vim macro with q, play it back with @ and a count, and turn a settings list into a .env file in seconds. Practise in a terminal in your browser.

Some edits are too irregular for :s and too boring to do by hand fifty times. A macro is Vim recording your keys and playing them back.

Record, then play

  1. qa starts recording into register a (any letter works). The status line says recording @a.
  2. Do the edit once, on one line, the way you'd do it by hand.
  3. q stops recording.
  4. @a plays it on the next line. @@ plays the last macro again, and a count plays it many times: 20@a.

Three habits that make macros work

  • Start from a known place. Begin the recording with 0 (start of the line), so it works wherever the cursor was left.
  • Move with motions, not arrows. f (find a character), w (next word) and iw (the word you're on) work on lines of any length; pressing the right arrow five times only works when the lines line up.
  • End on the next line. Finish with j, so each play sets up the next one. When there's no next line, j fails and the macro stops, so 100@a is a safe way to say "the rest of the file".

The keys for this lesson

settings.txt has lines like pool_size 10, and the app wants POOL_SIZE=10. On one line, by hand, that's:

0       go to the start of the line
gUiw    make the word under the cursor upper case (gU + iw)
f r=    find the space, replace it with =
j       down to the next line

So the macro is qa0gUiwf r=jq. Open the file with vim settings.txt and try it.

Tip:A macro is just text in a register. "ap puts it in the file to read or fix, and :reg a shows it.

Your turn

In settings.txt, record a macro that turns one line into NAME=value (the name in capitals), play it on the rest of the lines, and save.

Next