How do I copy all lines matching a pattern to the end of the file?
Answer
:g/pattern/t$
Explanation
How it works
The :g (global) command combined with :t (copy) lets you duplicate all lines matching a pattern to a specific location. The command :g/pattern/t$ finds every line matching pattern and copies it to the end of the file ($).
Breaking it down:
:g/pattern/selects all lines matching the patterntis the copy (transfer) command -- it copies a line to another location$is the destination address meaning end of file
You can copy to other locations too:
:g/pattern/t0copies matching lines to the top of the file:g/pattern/t15copies matching lines after line 15:g/pattern/t.copies matching lines after the current line
To move lines instead of copying, use m (move) instead of t:
:g/pattern/m$moves matching lines to the end of the file
Example
Suppose you have a log file and want to collect all error lines at the bottom:
[INFO] Server started
[ERROR] Connection timeout
[INFO] Request received
[ERROR] File not found
[INFO] Processing complete
Run:
:g/ERROR/t$
The file now has all error lines duplicated at the end:
[INFO] Server started
[ERROR] Connection timeout
[INFO] Request received
[ERROR] File not found
[INFO] Processing complete
[ERROR] Connection timeout
[ERROR] File not found
This is very useful for creating summaries, extracting specific data, or collecting items that match a criteria. Combine with :v (inverse global) to copy lines that do NOT match: :v/pattern/t$.