How do I execute a recorded macro a specific number of times?
Answer
5@q
Explanation
Prefix the @ macro-execution command with a count to run the macro that many times in a row. This is far faster than pressing @q repeatedly and works with any register.
How it works
5— the count prefix tells Vim to repeat the following command 5 times@q— execute the macro stored in registerq
Vim executes the macro back-to-back without stopping, as if you had typed @q@q@q@q@q. If the macro moves the cursor (e.g., j to the next line) or edits text conditionally, this becomes a concise way to batch-process multiple items.
You can also use @@ to re-run the last-used macro, so 10@@ repeats the most recently played macro 10 times.
Example
Suppose register q holds the macro I- <Esc>j (prepend a dash to the current line and move down). Running 5@q converts:
apple
banana
cherry
date
elderberry
into:
- apple
- banana
- cherry
- date
- elderberry
Tips
- If the macro might fail partway through (e.g., searching for a pattern that doesn't always exist), the count run stops at the first error — this is usually desirable behaviour.
- Use a deliberately large count like
999@qto run a macro until it hits an error (such as reaching the end of file), effectively processing the whole buffer. @@re-executes the last-used macro, so you can quickly resume with another count without retyping the register name.