Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 9 down vote accepted
awk '{print $NF,$0}' file.txt | sort -nr | cut -f2- -d' '
share|improve this answer
    
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
1  
@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 Apr 3 '11 at 11:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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