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
:sortsorts lines lexicographically (ascending by default)- The
uflag 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! usorts descending and removes duplicates:sort nsorts numerically;:sort nusorts numerically with deduplication:sort iignores case;:sort iuignores case and removes duplicates- To sort a range of lines, use
:5,20sort uor a visual selection:'<,'>sort u