How to move all the texts with a given pattern to the top of the file in Vim?

vim

Solution

Change `$` to `0`

:g/PATTERN/m0

If you want it in the same order as they are in the file run the command twice.

Or all at once. `execute` is needed since `g` can not be chained with bar. The second g command will use the same pattern as the first.

:exec 'g/PATTERN/m0' | g//m0

the command after the global command is `:move` which moves the current line to whatever address is supplied to move. `0` represents the first line in the file and `$` represents the last.

Problem

I know ``` g/PATTERN/m $ ``` will move all the texts with matching PATTERN to the end of the file. How do I accomplish the opposite? (i.e. to the top of the file)?

Original source