Is there a simple equivalent of :g/PATTERN/m0 that doesn't reverse the matched lines?
Occasionally I want to move all lines in a file to the top of that file. :g/PATTERN/m0
almost does what I want, but because :g
operates one line at a time in order, it will also reverse the affected lines.
Example:
Consider this file. Say I want to separate lines containing a number and move them to the top of the file. :g/\d/m0
does almost what I want (fr4nk, car0l and b0b are moved to the top) -- but it reverses the order of the matched lines.
alice
b0b
car0l
dan
eve
fr4nk
Actual output:
fr4nk
car0l
b0b
alice
dan
eve
Desired output:
b0b
car0l
fr4nk
alice
dan
eve
One way of doing what I want is to use :g/PATTERN/m$
(which won't reverse lines) and then move the lines from the bottom of the file to the top. Is there anything simpler?
Instead of moving matching lines to the top (reverses it), move none matching lines to the bottom
:v/\d/m$
It's not as easy as I would like it to be, but you can do something like this:
:let @a='' | exe 'g/\d/d A' | 0put a
The breakdown is that it clears register a
, executes a delete of all matching lines into register a
(uppercase appends to the register instead of replacing it), then puts the contents of register a
before the first line of the file.