How do I replay a macro multiple times in Vim?
Answer
10@a
Explanation
The 10@a command replays the macro recorded in register a exactly 10 times. By prefixing the macro replay command @a with a count, you can repeat any recorded macro as many times as you need, saving enormous amounts of repetitive work.
How it works
@areplays the macro stored in registera- Prefixing with a number like
10tells Vim to execute the macro that many times - Replace
10with any count andawith any register (a–z) where your macro is stored
Example
Suppose you record a macro in register a that deletes the first word of a line and moves down:
qa0dwjq
This records: go to beginning of line (0), delete word (dw), move down (j), then stops recording (q).
Given the text:
foo first line
bar second line
baz third line
qux fourth line
Running 3@a replays the macro 3 times, resulting in:
foo first line
second line
third line
fourth line
(Assuming the cursor started on bar second line.)
Tips
- Use
@@to replay the last executed macro without specifying the register name - Use
100@ato run a macro "until it fails" — Vim stops automatically when the macro encounters an error (like reaching the end of the file), so using a large count is a common idiom - In visual mode, use
:'<,'>normal @ato run the macro once on each selected line - Use
:5,20normal @ato run the macro on lines 5 through 20 - If the macro does not behave as expected, inspect its contents with
:reg aand edit it by pasting with"ap, modifying the text, and yanking it back with"ayy - Make sure your macro ends with the cursor in the right position for the next iteration — this is key to making counted replays work correctly