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

How do I collect all lines matching a pattern into a register without leaving them in place?

Answer

:g/pattern/d A

Explanation

Using :g/pattern/d A you can sweep through the entire buffer and extract every line that matches a pattern into register a, removing them from the buffer in the process. This is one of the most powerful data-extraction techniques in Vim, combining the :global command with the delete-to-register mechanism.

How it works

  • :g/pattern/ — run the following command on every line that matches pattern
  • d A — delete the line into register A (uppercase = append to register a)

Because uppercase register names append rather than overwrite, every matching line is accumulated in register a in order. After the command completes, :put a pastes all collected lines wherever you need them.

Setup: Before running, clear register a so you start fresh:

qaq

(qaq records an empty macro into register a, effectively clearing it.)

Example

Given a log file:

2024-01-01 INFO: server started
2024-01-01 ERROR: connection refused
2024-01-01 INFO: retrying
2024-01-01 ERROR: timeout
2024-01-01 INFO: done

Run:

qaq
:g/ERROR/d A
:put a

Result — the ERROR lines are removed from their original positions and placed at the cursor:

2024-01-01 ERROR: connection refused
2024-01-01 ERROR: timeout

Tips

  • To keep the original lines in place (non-destructive), use :g/pattern/y A (yank instead of delete)
  • Combine with :v/pattern/d A to collect lines that do not match
  • After collecting, sort the register contents with :'<,'>sort after pasting
  • For a dry run, use :g/pattern/p to preview matching lines before deleting

Next

How do I define autocmds safely so they don't duplicate when my vimrc is re-sourced?