Sort – GNU Sort Stable Sort When Sort Does Not Know Sort Order

sort

I have a two-column file; the file is sorted the way I want it on column 1 already. I would like to sort on column 2, within each column 1 category. However, sort does not understand the sort order of column 1.

The normal way (from similar questions here on stack) would be this:

sort --stable -k1,1 -k2,2n

But I cannot specify the sort on k1, because it is arbitrary.

Example input:

C 2
C 1
A 2
A 1
B 2 
B 1

and output:

C 1
C 2
A 1
A 2
B 1 
B 2

Best Answer

You could use awk to start a new sort for each block:

% awk -v cmd="sort -k2,2" '$1 != prev {close(cmd); prev=$1} {print | cmd}' foo
C 1
C 2
A 1
A 2
B 1
B 2
  • $1 != prev {close(cmd); prev=$1} - when the saved value is different, we have a new block, so we close any previously started sort
  • {print | "sort -k2,2"}' pipes the output to sort, starting it if it isn't already running (awk can keep track of commands it starts)
Related Question