3

For example I have some test file and want to sort it by the column values. After

awk -F'[:,]' '{print $16}' test.json

I get next output for the column 16:

 123
 457
 68
 11
 939
 11
 345
 9
 199
 13745

Now, when I want to sort it numeric, I use

awk -F'[:,]' '{print $16}' test.json | sort -nk16

but I just get back not nummeric sort...

 11
 11
 123
 13745
 199
 345
 457
 68
 9
 939

What is a reason, I thought -n parameter is enough for the nummeric sort....

  • 1
    Just sort -n. There's no 16th column in that output of awk – Stéphane Chazelas Sep 18 '14 at 14:35
  • Yes, it works. thank you. Anyway, if I want to sort the whole file by column 16, what I need to change in my command? Firstly I want create columns and sort by specific column the whole file. – Guforu Sep 18 '14 at 14:40
  • 1
    @Guforu you almost make it, try sort -nk16 test.json – Archemar Sep 18 '14 at 14:42
  • I did it, but it didn't work... I should first create a columns – Guforu Sep 18 '14 at 14:44
  • What do you mean by "create a columns"? Do you want to turn the : and , separators into spaces? Do you need the columns to line up in a readable format? Please be specific. – BobDoolittle Sep 18 '14 at 14:49
4

The output of awk contains only one column, so no 16th column.

So sort sees all identical empty sort keys and what you observe is the result of the last resort sort (lexical sort on the whole line) which you can disable with the -s option in some implementations.

Here you want:

awk -F'[:,]' '{print $16}' test.json | sort -n

Now, if you want to sort the file on the 16th column, beware sort supports only one character column delimiter, so you'd need to preprocess the input:

sed 's/[:,]/&+/g' test.json | sort -t+ -k16,16n | sed 's/\([:,]\)+/\1/g'

Here appending a + to every : or ,, sorting with + as the column delimiter and removing the + afterwards.

  • Thank you for your great answer. Anyway, what @Achemar tell, is also correct. – Guforu Sep 18 '14 at 14:59
  • 1
    @Guforu, sort's default column delimiter is the transition between a non-blank and a blank. So -k16n numerically sorts on the part of the line that goes from the 15th occurrence of that to the end of the line. For instance, in a line like " a b, 1 d, 2 e", -k3n would consider " 1 d, 2 e" as the sort key. Because of n, that's treated as 1, so -k3n is the same as -bk3,3n. – Stéphane Chazelas Sep 18 '14 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.