I have a large text file with several calls to a specific function method_name
.
I've matched them using :g/method_name
.
How would I move them to the top of the file (with the first match being on the top)?
I tried :g/method_name/normal ddggP
but that reverses the order. Is there a better way to directly cut and paste all the matching lines, in order?
Example input file:
method_name 1
foo
method_name 2
bar
method_name 3
baz
Example output file:
method_name 1
method_name 2
method_name 3
foo
bar
baz
How about trying it the other way around: moving the un-matched lines to the bottom:
:v/method_name/normal ddGp
This seems to achieve what you want.
I think you can achieve the desired result by first creating a variable assigned to 0:
:let i=0
And then executing this command:
:g/method_name/exec "m ".i | let i+= 1
It basically calls :m
passing as address the value of i, and then increments
that value by one so it can be used in the next match. Seems to work.
Of course, you can delete the variable when you don't need it anymore:
:unlet i
If the file is really large, count of matching entries is small, and you don't want to move around the entire file with solution v/<pattern>/ m$
, you may do this:
Pick any mark you don't care about, say 'k
. Now the following key sequence does what you want:
ggmk:g/method_name/ m 'k-1
ggmk
marks first line with 'k
.m 'k-1
moves matching line to 1 line before the 'k
mark (and mark moves down with the line it is attached to).This will only move a few matching lines, not the entire file.
Note: this somehow works even if the first line contains the pattern -- and I don't have an explanation for that.
For scripts:
normal ggmk
g/method_name/ m 'k-1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With