0

I have a file with two columns like:

12 c
16 a
50 b
32 b
15 c
25 c
...

I want to sort the table first based on second column, then descending sort the first column, then create the third column with 'rank.word'.

so output should look like:

16 a 1.a
50 b 1.b
32 b 2.b
25 c 1.c
15 c 2.c
12 c 3.c
...

the sorting part is easy, but any idea how to get the third column with basic shell command like awk?

1
  • Welcome to SO, not clear please be clear in your question add more details to it. Commented May 13, 2018 at 14:41

3 Answers 3

3

sort + awk solution:

sort -k2 -k1nr file | awk '{ print $1, $2, ++a[$2]"."$2 }'

The output:

16 a 1.a
50 b 1.b
32 b 2.b
25 c 1.c
15 c 2.c
12 c 3.c
Sign up to request clarification or add additional context in comments.

2 Comments

elegant, works well. but can i ask a dump question: what is ++a doing?
@jar-jar, it's called pre-increment operator. en.wikipedia.org/wiki/Increment_and_decrement_operators
0

awk '{if($2 != prev) idx=1;else idx++;prev=$2;print $1 " " $2 "." idx}'

Comments

0

One in GNU awk (2d array, for traverse order). It SEEMS to work at least with the data you provided but let me know if it didn't work with your real data.

$ awk '{
    a[$2][$1]++                               # hash data to a, count duplicates 
}
END {
    PROCINFO["sorted_in"]="@ind_str_asc"      # start with ordering $2 
    for(i in a) {
        PROCINFO["sorted_in"]="@ind_num_desc" # then $1
        for(j in a[i])
            for(k=1;k<=a[i][j];k++)           # handle duplicates
                print j,i,++c[i] "." i        # output
        PROCINFO["sorted_in"]="@ind_asc_asc"  # set order for $2 again
     }
}' file
16 a 1.a
50 b 1.b
32 b 2.b
25 c 1.c
15 c 2.c
12 c 3.c

Of course it fails if there are duplicate value pairs. It won't fail for duplicates anymore.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.