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
- 374 Use filter commands to process text
- 588 How to sort using visual blocks
- 758 Search and sort by selection
- 800 Sorting lines in a file based on the number of words in each line
- 923 Sort lines by a specified word number
- 1148 Unique sorting
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
works better in windows
:%s/^\(.*\)\(\n\1\)\+/\1/g :g/^$/d
- Note that the todo at the top of these Comments points out we should all be using Vim 7 now, and that makes this tip obsolete.
- To sort lines and remove duplicates in Vim 7:
:sort u