How do I move all lines matching a pattern to the end of the file in Vim?
Answer
:g/pattern/m $
Explanation
The :g (global) command combined with :m (move) lets you collect all lines matching a pattern and relocate them to a specific position in the file. This is extremely useful for reorganizing code — for example, moving all import statements to the top, gathering TODO comments to the bottom, or pulling all function definitions to one section.
How it works
:g/pattern/— Executes the following command on every line matchingpattern.m $— Moves the current line to the end of the file ($means the last line).- Lines are processed top-to-bottom, so their relative order is preserved in the destination.
Example
Gather all TODO comments to the end of a file:
:g/TODO/m $
Before:
func main() {
// TODO: add error handling
doStuff()
// TODO: add logging
doMore()
}
After:
func main() {
doStuff()
doMore()
}
// TODO: add error handling
// TODO: add logging
Tips
- Use
m 0to move matching lines to the top of the file instead. - Use
m 'ato move lines to just below marka— useful for collecting lines at a specific anchor point. - Combine with
:v(vglobal) to move lines that do not match::v/keep/m $. - To copy instead of move, use
:g/pattern/t $— this duplicates matching lines at the end.