How do I sort selected lines and remove duplicates in one command?
Answer
:'<,'>sort u
Explanation
:sort u sorts lines alphabetically and removes exact duplicate lines in a single operation. Select lines in visual mode, type : (which auto-fills :'<,'>), then sort u. The u flag means unique — after sorting, any consecutive duplicates are collapsed to one line.
Sort flags
| Command | Effect |
|---|---|
:sort |
Sort alphabetically (case-sensitive) |
:sort i |
Sort case-insensitively |
:sort u |
Sort and remove duplicate lines |
:sort! |
Sort in reverse order |
:sort n |
Sort numerically (by first number on each line) |
:sort /pattern/ |
Sort by text matching the pattern |
:sort iu |
Case-insensitive unique sort |
:sort! n |
Reverse numeric sort |
Example
Given:
banana
apple
cherry
apple
banana
Select all with ggVG, then :'<,'>sort u:
apple
banana
cherry
Sort a CSS file's properties alphabetically within a block:
vi{:sort
Tips
:sortwithout a range sorts the entire file; with:'<,'>it sorts only the selection:sort /.*\%2c/sorts by everything from column 2 onward (ignoring a leading character):sortis stable — lines that compare equal keep their original relative order- Combine with
:gfor advanced filtering::g/pattern/sortsorts blocks matching a pattern