vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Record a macro into register q that operates on a single line
  2. Run :g/pattern/normal @q to 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":

  1. Record the swap macro on one line: qq0dt,A,<Esc>p0q
  2. 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
  • :g processes 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

Next

How do I always access my last yanked text regardless of deletes?