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
- Enter visual line mode with
V - Select the lines you want to sort using
jork - Type
:sortand press<CR>— Vim fills in the range automatically as:'<,'>sort - 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.,2before10):sort u— sort and remove duplicate lines:sort /pattern/— sort by the text matching the pattern
Tips
- Use
:%sortto sort the entire file without needing a visual selection - Use
:sort!to reverse the sort order - Combine flags:
:sort iusorts case-insensitively and removes duplicates - Use
:sort nwhen sorting lines with numbers — withoutn,10would come before2because1<2lexicographically - Use
gvto reselect the same lines after sorting if you need to perform another operation - Unlike external
sort, Vim's:sortis a stable sort and works on any range of lines