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

How do I sort lines alphabetically in Vim?

Answer

:sort

Explanation

The :sort command sorts lines in the current buffer or a specified range alphabetically. It is a built-in alternative to the external sort command.

How it works

  • :sort sorts all lines in the buffer
  • :'<,'>sort sorts only the selected lines
  • :sort! sorts in reverse order
  • :sort u sorts and removes duplicate lines

Example

charlie
alpha
bravo

After :sort:

alpha
bravo
charlie

Tips

  • :sort n sorts numerically instead of alphabetically
  • :sort i sorts case-insensitively
  • :sort /pattern/ sorts by the text after the pattern match
  • :sort u removes duplicate lines while sorting
  • :%sort is equivalent to :sort (whole file)

Next

How do you yank a single word into a named register?