ascending and descending sort

Hi

I have a problem with sort command :

sort -nk 1.28,1.34 file | sort -nrk 1.27 file | sort -nk 1.22,1.25 file |sort -nk 1.13,1.21 file | sort -nk 1.9,1.12 file | sort -nk 1.1,1.8 file

This is the input file

0000000100010000000200004090317003
0000000100010000000230001020592002
0000000100010000000230001090588002
0000000100010000000200000090317003
0000000100010000000130001090588002
0000000200010000000100000090317003
0000000300010000000130001000592002

And the output file is

0000000100010000000130001090588002
0000000100010000000200000090317003
0000000100010000000200004090317003
0000000100010000000230001020592002
0000000100010000000230001090588002
0000000200010000000100000090317003
0000000300010000000130001000592002

descending sorting is not applied on field 27, and ascending sorting is not applied on field 28-34.

Thanks for your help

I can't understand your one-liner. But. To get ascending and descending sort order in the same sort:
example

sort -k1.1,1.10r  -k1.12,1.13 infile > outfile

The trailing "r" reverses the sort sequence for the one field only. In the example the first field. You can use a trailing "n" and many of the other qualifiers to change sort behavior on a per field basis.

also note: sort -k 1.27 means not a single character in the field - it means the field is the whole line from position 27 all the way to the end.

1 Like

I think those successive sorts keep overriding the order that resulted from the prior commands.

$
$ cat f55
10~123
10~099
10~880
12~451
12~110
09~009
09~101
$
$ sort -t"~" -nk2,2 f55
09~009
10~099
09~101
12~110
10~123
12~451
10~880
$
$ # numeric ascending sort of 2nd field; "~" being the delimiter
$
$ sort -t"~" -nk2,2 f55 | sort -t"~" -nrk1,1
12~451
12~110
10~880
10~123
10~099
09~101
09~009
$
$ # numeric descending sort of 1st field; "~" being the delimiter
$ # but the order resulting from the first sort is lost now
$

Ultimately, all I could figure out is that your data has the first 8 characters sorted in numerically ascending order since that's the last sort command in the pipeline.

tyler_durden

1 Like

Yes, There is a problem with successive sorts. I don't know how is the priority is managed in this case.

I changed the sort command like that and it's ok now :

cat "$1" |sort -nk 1.1,1.8 -k 1.9,1.12 -k 1.13,1.21 -k 1.22,1.25 -k 1.28,1.34 -k 1.27r > "$1"_tmp

Thanks for your help
Fafa