AWK. Calculate mean, min and max

Oct 23, 2008 by     11 Comments    Posted under: Linux/Unix, Tutorials

AWK is a general purpose programing language that is designed for processing text-based data. This unix command is very powerful and with it we can calculate the mean, min and max of a data stored in file.

data.txt:

10
20
50
100
200
500

awk command:

awk ‘{if(min==”"){min=max=$1}; if($1>max) {max=$1}; if($1< min) {min=$1}; total+=$1; count+=1} END {print total/count, min, max}’ data.txt

Result:

146.667 10 500

11 Comments + Add Comment

  • Very useful ;)

  • A small gift for you. This awk program is an extension of yours that accept different column numbers and also print the line index where min and max values occur.

    #get-mean-min-max.awk
    #You must define COL with option -v of awk
    {
    if(min==”")
    {
    min=max=$COL
    };

    if($COL>max)
    {
    max=$COL
    maxIdx=NR
    };

    if($COL< min)
    {
    min=$COL
    minIdx=NR
    };

    total+=$COL;
    count+=1
    }

    END {print total/count "\n" min " – " minIdx "\n" max " – " maxIdx}

  • awk ‘{if(min==””)min=max=$1}; if($1>max) {max=$1}; if($1< min) {min=$1}; total+=$1; count+=1} END {print total/count, min, max}’ data.txt

  • I had been looking for this function for ages, and this is it (and even more than I was looking for)!! thanks

  • [...] Solution I made with the help of these guides 1 and 2 is given below. Save the lines between the ###### as a file, say meanminmax. [...]

  • [...] Solution I made with the help of these guides 1 and 2 is given below. Save the lines between the ###### as a file, say meanminmax. [...]

  • Amazing blog:) I am going to want a bit of time to toy with this article!

  • The single quotes around the script cause a “bash: syntax error near unexpected token ‘(‘ ” to occur when dragging and dropping the script on some computers. This is easily fixed by deleting and replacing them with single quotes from your keyboard. The first double quote causes another error, “invalid character …” to appear just before the END block. Fix it the same way, replace the first ” with one from your keyboard.

    Total/Count is the Average but not the statistical mean.

  • [...] Since you’re already using awk [...]

  • OMG .. i don’t have other words :)

  • Nice, clean , simple , see below:

    awk -F ‘;’ ‘{if(min==””){min=max=$2}; if($2>max) {max=$2}; if($2< min) {min=$2}; total+=$2; count+=1} END {print total/count, min, max}’ data.txt

Got anything to say? Go ahead and leave a comment!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Category

Polls

How Is My Site?

View Results

Loading ... Loading ...

Twitter: damiles3D

  • Could not connect to Twitter