Vim Tips Wiki
Advertisement

Previous TipNext Tip

Tip: #1166 - Sort lines

Created: March 9, 2006 7:25 Complexity: basic Author: Robert Stovall in Dallas Version: 5.7 Karma: 29/17 Imported from: Tip#1166

This is just a reminder of how to take advantage of existing VIM capability. I had not needed to sort before and took a few minutes to find a good example.


Sort lines in vim using blocks:


<range>!sort


Yes, its that simple.


Key strokes:


1) Place cursor at first line of range to be sorted.

2) Use marker (ma) to mark starting point

3) Go to last line of range to be sorted

4) Issue command from marker (a) to here as follows:

'a,.!sort



Hope this little reminder helps.

Comments

Use "V" and highlight the lines you want (instead of marks), then :!sort.

Anonymous , March 9, 2006 7:34


Note that for vim <7, this uses the external sort program. This has some consequences:

- the program must be installed (which it usually is) - options can be passed to it

which means you can do (for example)

!sort -n

to sort numerically,

!sort -k2

to sort on the second field, etc

Anonymous , March 9, 2006 14:21


Just to point out that sort is a *nix utility. windows users will need to get sort.exe from http://www.cygwin.com/ or http://unxutils.sourceforge.net/

To sort whole file, and delete duplicates

%!sort -u

the ! here means access external utility


zzapper , March 10, 2006 4:03


Check :help eval-examples

It has (as an example) a vim function called :Sort by Robert Webb that doesn't require an external sort utility.

- Karthick

Anonymous , March 12, 2006 19:37


See also VimTip305, VimTip374, and VimTip588.

mfo--AT--sympatico.ca , March 13, 2006 10:53


To remove duplicate lines from a sorted list (make each line unique):

%s/^\(.*\)\(\n\1\n\)\+/\1/g


org.vim--AT--pooryorick.com , July 14, 2006 11:20


to remove duplicates from a sorted list use uniq is simpler:

%!sort|uniq

is a binary installed almost everywhere


Advertisement