In the buffer
Before:
apple
banana
apple
cherry
banana
date
After running :sort u:
apple
banana
cherry
date
When you would reach for it
You have a list of things. Lines of configuration, import statements, package names, whatever. Some are duplicates. You want them alphabetically sorted and you want each entry to appear exactly once.
The old way: :sort, then manually hunt for duplicates. Or pipe the buffer through sort | uniq and pull it back in. The new way: :sort u. One command, no external dependencies, no temporary files.
Gotchas
:sort uconsiders lines duplicates only if they are identical after sorting brings them together. It does not fuzzy-match or trim whitespace by default.- Leading whitespace matters.
" apple"and"apple"are different lines and will both remain after:sort u. - The
uflag must come aftersort, not before.:u sortis not valid. - To sort only a visual selection, first select the lines in visual mode, then type
:. Vim will populate the command line with:'<,'>automatically. Addsort uafter that to sort just the selection.
Variants
Case-insensitive sort (:sort iu): Treats uppercase and lowercase as the same. Apple and apple become duplicates.
Numeric sort (:sort nu): Sorts by numeric value instead of alphabetical order. Useful for lists of numbers where 10 should come after 9, not after 1.
Before:
10
2
1
After :sort n:
1
2
10
Reverse sort (:sort! u): Sorts in descending order and removes duplicates. The ! inverts the sort direction.
Sort by pattern (:sort /pattern/ u): Sorts based on the text matching a regex pattern, not the whole line. Advanced usage for structured data.
The :sort command works on ranges. You can sort specific line ranges like :10,20sort u (lines 10 through 20) or :%sort u (entire file, though this is the default when no range is given).