Vim Tips Wiki
(Move categories to tip template)
(Remove html character entities)
Line 16: Line 16:
 
Sort lines in Vim using blocks:
 
Sort lines in Vim using blocks:
 
<pre>
 
<pre>
:&lt;range&gt;!sort
+
:<range>!sort
 
</pre>
 
</pre>
   
Line 46: Line 46:
   
 
----
 
----
Note that for Vim &lt;7, this uses the external sort program. This has some consequences:
+
Note that for Vim <7, this uses the external sort program. This has some consequences:
 
*The program must be installed (which it usually is).
 
*The program must be installed (which it usually is).
 
*Options can be passed to it.
 
*Options can be passed to it.

Revision as of 23:59, 29 September 2008

Tip 1166 Printable Monobook Previous Next

created March 9, 2006 · complexity basic · author Robert Stovall · version 5.7


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, it's that simple.

Key strokes:

  • Place cursor at first line of range to be sorted.
  • Use marker (ma) to mark starting point
  • Go to last line of range to be sorted
  • Issue command from marker (a) to here with :'a,.!sort

See also

References

Comments

 TO DO 
Update tip for Vim 7. It is now almost always better to use the :sort command that is built into Vim: Use flag n to sort numerically or u to keep unique lines.


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


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.


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


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

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