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

How do I run a macro on all lines matching a pattern?

Answer

:g/pattern/norm @a

Explanation

The :g/pattern/norm @a command combines the global command with macro execution. It runs macro a on every line matching the pattern.

How it works

  • :g/pattern/ selects all matching lines
  • norm @a executes macro a on each line in normal mode
  • The macro runs with the cursor at the beginning of each matching line

Example

Add a TODO comment to every line containing FIXME:

qaA // TODO<Esc>q
:g/FIXME/norm @a

Tips

  • Use norm! to avoid interference from custom mappings
  • The macro should work on a single line without jumping to other lines
  • :v/pattern/norm @a runs on non-matching lines
  • This is more targeted than using a count with @a

Next

How do you yank a single word into a named register?