How do I run a macro on every line matching a pattern?
Answer
:g/pattern/normal @q
Explanation
The :global command combined with :normal lets you execute a recorded macro on every line that matches a given pattern. This is one of Vim's most powerful batch-editing techniques.
How it works
- Record a macro into register
qthat operates on a single line - Run
:g/pattern/normal @qto apply it to every matching line
Example
Suppose you have a CSV file and want to swap the first and second columns on every line containing "ERROR":
- Record the swap macro on one line:
qq0dt,A,<Esc>p0q - Apply to all ERROR lines:
:g/ERROR/normal @q
Variations
" Run macro on lines NOT matching a pattern
:g!/pattern/normal @q
:v/pattern/normal @q
" Run macro on a range
:10,50g/pattern/normal @q
" Combine with other ex commands
:g/TODO/execute "normal @q" | s/TODO/DONE/
Tips
- The macro should be self-contained and not depend on cursor position across lines
:gprocesses lines top-to-bottom by default- Use
:v(short for:g!) to match lines that do NOT contain the pattern - This technique replaces complex find-and-replace when the transformation isn't a simple substitution