Reman
Reman

Reputation: 8119

How to sort by 2 different columns?

I want to sort a text by 2 different columns:

aaa5aaaaa
aaa3azaba
aaa4aaaaa
aaa3abaza

The 1st sort must be only at column 4 and if there are equal numbers p.e. in above example '3' the 2nd sort must be at column 8 and if there are still the same characters the next column must be 9 etc.

I thought that this would be the solution:

%sort i /\%4v\|\%8v/

but it doesn't work.

Output:

aaa3abaza
aaa3azaba
aaa4aaaaa
aaa5aaaaa

Expected Output:

aaa3azaba
aaa3abaza
aaa4aaaaa
aaa5aaaaa

Upvotes: 2

Views: 147

Answers (2)

Kent
Kent

Reputation: 195169

this line:

sor /\%7v/|sor n /\%3v/

works for your example.

it does two sorting, first sort by col8, then sort by col4 (as number).

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172648

Here's what's wrong with your attempt:

  • The /pattern/ argument to the built-in :sort specifies the text to skip; you're apparently attempting to match certain columns.
  • The \%v atom is zero-width, so you'd probably need to append a . to make it match the character (if this would work despite the first point).
  • I don't think that there's a way to specify multiple search keys (i.e. your character positions 4 and 8) with the built-in :sort at all.

If you have GNU sort installed (i.e. Linux system or via Cygwin), you can use this external command:

:%!sort -k1.4,1.4 -k1.8,1.8

This specifies the two character columns 4 and 8 as offsets of the first field (1.) as sort keys.

Upvotes: 3

Related Questions