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
- Clear the register first:
qaq(record empty macro intoa) - Run
:g/pattern/y Ato collect matching lines - 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
qaqor: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