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

How do I sort lines and remove duplicates in Vim?

Answer

:%sort u

Explanation

The :sort u command sorts all lines in the file and removes duplicate lines in one operation. The u flag stands for "unique" — it keeps only the first occurrence of each duplicate line.

How it works

:%sort u      " Sort entire file, remove duplicates
:'<,'>sort u  " Sort selected lines, remove duplicates
:10,20sort u  " Sort lines 10-20, remove duplicates

Example

Before:

banana
apple
cherry
apple
banana
date

After :%sort u:

apple
banana
cherry
date

Sort options

:sort           " Alphabetical sort
:sort!          " Reverse sort
:sort i         " Case-insensitive sort
:sort n         " Numeric sort (10 comes after 9, not after 1)
:sort f         " Float sort
:sort /pattern/ " Sort by text matching pattern
:sort u         " Unique (remove duplicates)

Advanced: Sort by a specific field

" Sort CSV by second column
:sort /[^,]*,/

" Sort by the number at the end of each line
:sort /\d\+$/

Tips

  • Combine flags: :sort! iu for reverse, case-insensitive, unique sort
  • :sort works on visual selections — select lines first, then type :sort u
  • Unlike shell sort -u, Vim's :sort u preserves the original line content exactly
  • For removing duplicates without sorting, use :g/^\(.*\)$\n\1$/d (adjacent duplicates only)

Next

How do I always access my last yanked text regardless of deletes?