← back to latest

Sort a list and drop the duplicates in one pass

COMMAND:sort uSort a list and drop the duplicates in one pass

anatomy

:
Enter command-line mode.
sort
The sort command. Operates on the current range (defaults to whole file).
u
Unique flag. Removes duplicate lines after sorting.

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 u considers 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 u flag must come after sort, not before. :u sort is 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. Add sort u after 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).

lineage

The :sort command was added to Vim 7.0 (2006). Before that, users had to pipe text through external Unix sort utilities or write custom scripts.

-- INSERT --vim-hacks.com001-001-sort-u.html
utf-81,1All