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

How do I sort selected lines in Vim?

Answer

:'<,'>sort

Explanation

The :'<,'>sort command sorts the currently selected lines in visual mode alphabetically. Select lines with V, then type :sort and Vim automatically fills in the '<,'> range markers to operate on your selection.

How it works

  1. Enter visual line mode with V
  2. Select the lines you want to sort using j or k
  3. Type :sort and press <CR> — Vim fills in the range automatically as :'<,'>sort
  4. The selected lines are sorted in ascending alphabetical order

Example

Given the text:

charlie
alpha
delta
bravo

Select all four lines with ggVG, then type :sort<CR>. The result:

alpha
bravo
charlie
delta

Sort options

  • :sort — ascending alphabetical order (default)
  • :sort! — descending (reverse) alphabetical order
  • :sort i — case-insensitive sort
  • :sort n — sort by numeric value (e.g., 2 before 10)
  • :sort u — sort and remove duplicate lines
  • :sort /pattern/ — sort by the text matching the pattern

Tips

  • Use :%sort to sort the entire file without needing a visual selection
  • Use :sort! to reverse the sort order
  • Combine flags: :sort iu sorts case-insensitively and removes duplicates
  • Use :sort n when sorting lines with numbers — without n, 10 would come before 2 because 1 < 2 lexicographically
  • Use gv to reselect the same lines after sorting if you need to perform another operation
  • Unlike external sort, Vim's :sort is a stable sort and works on any range of lines

Next

How do I edit multiple lines at once using multiple cursors in Vim?