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

How do I collect all lines matching a pattern and copy them to the end of the file or a register?

Answer

:g/pattern/yank A

Explanation

The :g command combined with yank A (uppercase A to append) lets you collect every line matching a pattern into a single register without overwriting previous contents. This is a powerful way to extract matching lines from a large file — log entries, TODO comments, function signatures — and paste them all together in one place.

How it works

  • :g/pattern/ selects every line in the file that matches pattern
  • yank A yanks each matching line and appends it to register a (uppercase register name means append)
  • After the command completes, register a contains all matching lines concatenated together
  • Paste them with "ap wherever you need them

The key detail is the uppercase A — lowercase a would overwrite the register with each line, leaving only the last match. Uppercase appends, so every match accumulates.

Example

Given a source file:

import os
import sys

def hello():
    print("hello")

import json

def goodbye():
    print("goodbye")

import re

First clear register a with qaq, then collect all import lines:

:g/^import/yank A

Now "ap pastes:

import os
import sys
import json
import re

All four import lines were collected from scattered locations into one block.

Alternative: copy to end of file

Instead of collecting into a register, you can copy matching lines directly to the end of the file:

:g/pattern/t$

This uses :t (copy) to duplicate each matching line after the last line, gathering them all at the bottom of the file.

Tips

  • Always clear the register first with qaq (record nothing into register a) before collecting — otherwise you append to whatever was already in the register
  • Use :g/pattern/t0 to collect matching lines at the top of the file instead of the bottom
  • Use :g/pattern/m$ to move (not copy) matching lines to the end — this removes them from their original positions
  • Combine with :v (inverse global) to collect non-matching lines: :v/pattern/yank A collects every line that does NOT match
  • Use :g/TODO\|FIXME\|HACK/yank A with alternation to collect lines matching any of several patterns
  • After collecting into a register, you can paste into a scratch buffer (:enew | put a) for further processing
  • This technique is often called "grep inside Vim" — it extracts matching lines without any external tools

Next

How do I edit multiple lines at once using multiple cursors in Vim?