How to sort numeric and literal columns in Vim

VimSorting

Vim Problem Overview


Using Vim 6.0. Say I'm editing this file:

sdfsdg
dfgdfg

34     12
2      4
45     1
34     5

How do I sort the second column?

Vim Solutions


Solution 1 - Vim

If you have decent shell available, select your numbers and run the command

:'<,'>!sort -n -k 2

If you gonna type this in visual mode, after typing the colon, markers '<,'> will appead automatically, and you'll only have to type the rest of it.

This type of commands (:[motion]!) is called filtering. You can learn more by consulting vim's help:

:h filter

Solution 2 - Vim

Sort all lines on second column N by using Vim sort command, e.g.

:sort /.*\%2v/ 

Reference: vimtips.txt

Solution 3 - Vim

For vim7 I would go for:

:sort n /.*\s/

This will sort numbers ignoring text matched by given regexp. In your case it is second column.

Solution 4 - Vim

Sort by 2nd column by selecting it in visual mode (e.g. Control+v), then run:

!sort

or to sort by third column

sort -k 3 

or

:sort /.*\%3v/

Alternatively select the lines you wish to sort using the Shift+V command. Then enter

!sort -k 3n

or use the below code to tell Vim to skip the first two words in every line and sort on whatever follows:

:%sort /^\S\+\s\+\S\+\s\+/ 

or i.e. sort by 8th line:

:sort /.*\%55v/

The 'virtual' specification is the absolute number of column , which treats spaces + tabs as single character (shortly, it doesn't count tabs as eight spaces),

so to sort by last column:

:%sort /\<\S\+\>$/ r

Solution 5 - Vim

If more columns were there, you may use repetition to avoid complicated pattern.
For example, this will sort the entire file by the 100th column ("column" here means the space separated column)

:%sort /^\(\S\+\s\+\)\{99}/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvehomzzzView Question on Stackoverflow
Solution 1 - VimP ShvedView Answer on Stackoverflow
Solution 2 - Vimmschmidt42View Answer on Stackoverflow
Solution 3 - VimMaxim KimView Answer on Stackoverflow
Solution 4 - VimT.ToduaView Answer on Stackoverflow
Solution 5 - VimKen.HView Answer on Stackoverflow