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?
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?
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
V
to select a range, then typed :
, which automatically inserts the visual selection range '<,'>
, and then typed the actual command !sort -n -k 2
. You can of course specify the range in any way - see :help range
if you're curious. –
Courtier -h
flag for human-readable numerals to show largest files at the top: :'<,'>!sort -hr
–
Deodand sort -n -k 2
will sort using column two till the end of the line. Use sort -n -k 2,2
to only sort by column two. Adding more pairs of -k for additional columns. Sometimes that still fails to leave them in the stable order. In that case, use sort's -s/--stable
option. –
Edgington Sort all lines on second column N by using Vim sort
command, e.g.
:sort /.*\%2v/
Reference: vimtips.txt
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.
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
sort!
is nice as well. –
Ecology 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}/
© 2022 - 2024 — McMap. All rights reserved.
:sort n
, as the help says: "With [n] ... sorting is done on the first decimal number in the line..." This doesn't apply to your case, but might to somebody elses. – Crabstick