• Uncategorized

About linux : How-to-add-a-new-column-with-the-correct-order-in-awk-taking-into-account-that-the-same-position-may-be-repeated-closed

Question Detail

I am trying to generate a new column with the new ranking position for a series of millionaires. The problem is that many of them have the same amount of money and when I generate a list with the order as follows: NR>1{$0=$0", "NR-1} 1, it doesn’t take me into account if there are more than one or two millionaires with the same amount of money.

What I want to do would be for example to order something like this:

Name;Company;Billions    
Bill Gate;Microsoft;76
Manolo Chocolatero;Churrerias;2
Eduardo Mendoza;ED S.A;3
Juan Palotes;Circos S.A;2

Output:

Name;Company;Billions;Ranking    
Bill Gate;Microsoft;76;1
Manolo Chocolatero;Churrerias;3;2
Eduardo Mendoza;ED S.A;2;3
Juan Palotes;Circos S.A;2;3

Any idea how to do this with awk?

Question Answer

awk allows you to use variables, e.g. one for the rank, and one for the last value. With that, you can increase the rank only if the current value differs from the last one (assuming that you sort the input previously).

awk -F\; -v OFS=\; 'NR == 1 { $(NF + 1) = "Ranking" }
            NR > 1 { ++a[$NF]; $(NF + 1) = length(a) } 1' file

Apply sort if they aren’t sorted.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.