vehomzzz
vehomzzz

Reputation: 44598

How to sort numeric and literal columns in Vim

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?

Upvotes: 63

Views: 53799

Answers (5)

Ken.H
Ken.H

Reputation: 3

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}/

Upvotes: 0

mschmidt42
mschmidt42

Reputation: 1095

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

:sort /.*\%2v/ 

Reference: vimtips.txt

Upvotes: 51

T.Todua
T.Todua

Reputation: 56487

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

Upvotes: 24

P Shved
P Shved

Reputation: 99344

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

Upvotes: 66

Maxim Kim
Maxim Kim

Reputation: 6392

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.

Upvotes: 26

Related Questions