Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum and Minimum using awk

Tags:

unix

max

awk

min

How would you find the maximum and minimum a,b,c values for the rows that start with MATH from the following file?

TITLE     a       b       c
MATH      12.3    -0.42   5.5
ENGLISH   70.45   3.21    6.63
MATH      3.32    2.43    9.42
MATH      3.91    -1.56   7.22
ENGLISH   89.21   4.66    5.32

It can not be just 1 command line. It has to be a script file using BEGIN function and END.

I get the wrong minimum value and I end up getting a string for max when I run my program. Please help!

Here is my code for the column a:

BEGIN { x=1 }
{
 if ($1 == "MATH") {
        min=max=$2;
        for ( i=0; i<=NF; i++) {
                min = (min < $i ? min : $i)
                max = (max > $i ? max : $i)
        }
 }

}

END { print "max a value is ", max, " min a value is ", min }

Thanks!

like image 548
mika Avatar asked Sep 10 '13 01:09

mika


2 Answers

This code could demonstrate a concept of what you want:

awk '$1!="MATH"{next}1;!i++{min=$2;max=$2;}{for(j=2;j<=NF;++j){min=(min<$j)?min:$j;max=(max>$j)?max:$j}}END{printf "Max value is %.2f. Min value is %.2f.\n", max, min}' file

Output:

MATH      12.3    -0.42   5.5
MATH      3.32    2.43    9.42
MATH      3.91    -1.56   7.22
Max value is 12.30. Min value is -1.56.

Remove 1 to suppress the messages:

awk '$1!="MATH"{next};...

Script version:

#!/usr/bin/awk

$1 != "MATH" {
    # Move to next record if not about "MATH".
    next
}
!i++ {
    # Only does this on first match.
    min = $2; max = $2
}
{
    for (j = 2; j <= NF; ++j) {
        min = (min < $j) ? min : $j
        max = (max > $j) ? max : $j
    }
}
END {
    printf "Max value is %.2f. Min value is %.2f.\n", max, min
}
like image 64
konsolebox Avatar answered Sep 28 '22 11:09

konsolebox


look at your for loop

it starts from i=0 so the condition should be

i<NF 

instead of

i<= NF

try the following line instead of that line .... i hope you get what u are looking for

for(i=0;i<NF;i++){

rest all looks fine to me.... thanks

like image 34
nikhil Avatar answered Sep 28 '22 13:09

nikhil