23

I have this input:

sdkxyosl 1
safkls 2
asdf--asdfasxy_asd 5
dkd8k  jasd 29
sdi44sw 43
asasd afsdfs 10
rklyasd 4

I need this output:

sdi44sw 43
dkd8k  jasd 29
asasd afsdfs 10
asdf--asdfasxy_asd 5
rklyasd 4
safkls 2
sdkxyosl 1

So i need to sort the lines by the last column.

I don't know how many columns are in one line.

I just can't figure it out, how to do it. I don't have "perl powers". I just have ~average scripting powers with sed, awk, cut, etc..

Does somebody know how to do it?

34

The following command line uses awk to prepend the last field of each line of file.txt, does a reverse numerical sort, then uses cut to remove the added field:

awk '{print $NF,$0}' file.txt | sort -nr | cut -f2- -d' '
  • omg...i didn't knew about the $RS!! thank you very much!!!!! – LanceBaynes Apr 2 '11 at 20:48
  • @forcefsck: I don't think it's possible with only sort -k. The begfield function in GNU sort just counts down to zero. Your decorate-sort-undecorate (DSU) approach seems to be the best way I think. – Mikel Apr 2 '11 at 23:20
  • Out of interest, why $NF,$RS and not $NF,$0? I didn't know $RS did that. (I guess it's equivalent to $NF,$"\n", which does the same, but that's also surprising I think.) – Mikel Apr 3 '11 at 0:36
  • 2
    @johnny8888, @forcefsck: In awk, $ can be followed by any expression. “The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified”. GNU awk (on my system) treats a string like "\n" as zero. Others (e.g. the original implementation by A, W and K) abort with an error message. If RS happened to be a digit, you'd get the corresponding field on any implementation. So don't do this, use $0. – Gilles 'SO- stop being evil' Apr 3 '11 at 11:51
  • 1
    Really neat! So the long explanation of what is going on: with awk, print the last field first then the whole record, sort in reverse numerically, then trim off the first column using cut. – phyatt Nov 7 '16 at 15:00

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.