Vim macros: record an edit once, play it a hundred times
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
qastarts recording into register a (any letter works). The status line saysrecording @a.- Do the edit once, on one line, the way you'd do it by hand.
qstops recording.@aplays 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) andiw(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,jfails and the macro stops, so100@ais 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.
Your task
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.
- Record a macro (not done yet)
- Play it (not done yet)
- Every line is NAME=value, saved (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
vim- Edit text files in the terminal (a practice subset of Vim) More on vim
qa- Vim: record everything you type into register a; press q again to stop
@a- Vim: play the keys in register a; @@ plays the last macro again, 10@a plays it ten times
Every everyday command on one page: the Linux commands cheat sheet.