vimtricks.wiki Concise Vim tricks, one at a time.

How do I sort lines and remove duplicates in one command?

Answer

:sort u

Explanation

The :sort u command sorts all lines in the buffer (or a selected range) alphabetically and removes duplicate lines in a single pass. The u flag stands for unique — Vim discards any line that is identical to the one preceding it after sorting.

How it works

  • :sort sorts lines lexicographically (ascending by default)
  • The u flag removes consecutive duplicate lines after the sort, eliminating all exact duplicates
  • To sort a visual selection only, use :'<,'>sort u

Example

Given this buffer:

banana
apple
cherry
apple
banana

Running :sort u produces:

apple
banana
cherry

Tips

  • :sort! reverses the order (descending); :sort! u sorts descending and removes duplicates
  • :sort n sorts numerically; :sort nu sorts numerically with deduplication
  • :sort i ignores case; :sort iu ignores case and removes duplicates
  • To sort a range of lines, use :5,20sort u or a visual selection :'<,'>sort u

Next

How do I run text I've yanked or typed as a Vim macro without recording it first?