Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move lines matched by :g to the top of the file

Tags:

vim

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
like image 793
Dogbert Avatar asked Jul 01 '11 22:07

Dogbert


3 Answers

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.

like image 83
Prince Goulash Avatar answered Nov 19 '22 09:11

Prince Goulash


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
like image 36
sidyll Avatar answered Nov 19 '22 10:11

sidyll


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
like image 1
t7ko Avatar answered Nov 19 '22 10:11

t7ko