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

How do I collect all lines matching a pattern into a register?

Answer

:g/pattern/y A

Explanation

The :g/pattern/y A command yanks every line matching the pattern and appends it to register a. The uppercase A is the key — it appends rather than overwrites, so each matching line accumulates in the register.

How it works

  1. Clear the register first: qaq (record empty macro into a)
  2. Run :g/pattern/y A to collect matching lines
  3. Paste the collected lines: "ap

Example

Given a source file:

import os
class MyClass:
    def method_one(self):
        pass
    def method_two(self):
        pass
import sys
    def method_three(self):
        pass

To extract all method definitions:

qaq                     " Clear register a
:g/def /y A             " Yank all matching lines into a
"ap                     " Paste collected lines

Result:

    def method_one(self):
    def method_two(self):
    def method_three(self):

Variations

" Collect into a new buffer
:g/pattern/y A | new | put a

" Collect lines NOT matching
:v/pattern/y A

" Collect with surrounding context (yank 2 lines after each match)
:g/pattern/.,+2y A

Tips

  • Always clear the register first with qaq or :let @a = ''
  • This technique is great for extracting function signatures, TODOs, error messages, or any pattern from large files
  • Use :g/pattern/t$ if you want to copy matching lines to the end of the file instead of a register

Next

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