AWK-Find maximum value in a row & print with header

awktext processingtext;

I need to read a file, find the maximum value in each row, and print the ID of the row, the column the maximum value came from (sno#), and the value from the associated lc# column. If the maximum value occurs more than once, I need to include all matches. For example:

input.txt (tab-delimited)

Id  sno1  lc1  sno2  lc2    sno3  lc3  sno4 lc4
RM1  98   ss1   88   ms1    78    gs1   45  rs1
RM2  23   ss2   44   ms2    98    gs2   15  rs2
RM3  45   ss3   100  ms3    33    gs3   10  rs3
RM4  45   ss4   45   ms4    12    gs4   11  rs4

output.txt

RM1 ss1 sno1
RM2 gs2 sno3
RM3 ms3 sno2
RM4 ss4,ms4 sno1,sno2   

Best Answer

input

$ cat input.txt
Id  sno1  lc1  sno2  lc2    sno3  lc3  sno4 lc4
RM1  98   ss1   88   ms1    78    gs1   45  rs1
RM2  23   ss2   44   ms2    98    gs2   15  rs2
RM3  45   ss3   100  ms3    33    gs3   10  rs3
RM4  45   ss4   45   ms4    12    gs4   11  rs4

awk script

$ cat row_max.awk
NR == 1 {
        for (i = 1; i <= NF; i++) headers[i] = $i;
        next
}

{
        # find maximum value
        max = $2
        for (i = 4; i <= NF; i += 2) if ($i > max) max = $i;
        # print row id
        printf "%s", $1
        # print all lc# column values (assuming the column 
        # after the max value sno# column)
        sep = OFS
        for (i = 2; i <= NF; i += 2) {
                if ($i == max) {
                        printf "%s%s", sep, $(i + 1);
                        sep = ","
                }
        }
        # print all column headers of the max value columns
        sep = OFS
        for (i = 2; i <= NF; i += 2) {
                if ($i == max) {
                        printf "%s%s", sep, headers[i];
                        sep = ","
                }
        }
        printf "\n"
}

output

$ awk -f row_max.awk input.txt
RM1 ss1 sno1
RM2 gs2 sno3
RM3 ms3 sno2
RM4 ss4,ms4 sno1,sno2
Related Question