Dominik
Dominik

Reputation: 33

Finding max value using AWK

I have a file with two column data and I want to find the max value and print it. file =load_measure

11:20,18.03
11:25,17.85
11:30,18.24
11:35,19.19
11:40,18.45
11:45,17.53
11:50,17.56
11:55,17.60
12:00,18.51
12:05,18.50

I try via hereunder code but It returns 0

awk 'BEGIN {max = 0} {if ($2>max) max=$2} END {print max}' load_measure
0

I try via declaring max as $max but it does not count the real max:

awk 'BEGIN {max = 0} {if ($2>max) max=$2} END {print $max}' load_measure
12:05,18.50

Can anyone explain what I'm doing wrong? thank you!

Upvotes: 2

Views: 1585

Answers (2)

Ed Morton
Ed Morton

Reputation: 203502

When your fields are separated by something other that white space you need to tell awk what that something is by populating FS. You also need to set max to the first value read so the script will work for all-negative input and you need to print max+0 in the END to ensure numeric output even if the input file is empty:

awk -F, 'NR==1{max=$2} $2>max{max=$2} END{print max+0}' file

Whern max is 2, print max is printing the value of max, i.e. 2, while print $max is printing the value of the field indexed by the value of max, i.e. $2, which in an END section will either be null or the value of $2 on the last line read (undefined behavior per POSIX so awk-dependent).

Upvotes: 3

Zsolt Botykai
Zsolt Botykai

Reputation: 51603

You should specify the value of FS that is the input field separator. It describes how each record is split into fields; it may even be an extended regular expression.

On awk's command line, FS can be specified as -F <sep> (or -v FS=<sep>). You can also set it in the BEGIN block.

I'm normally using the later method but that's just a personal preference:

BEGIN {max=0;FS=","} ....

Also Your problem can be solved like this too:

awk -F, -v m=0 '$2>m {m=$2} END {print m}' 

thus sparing an if statement.

The POSIX-mandated default value is a space (0x20). But be aware that running spaces (more than one) might be considered as one field separator.

Here is the official documentation for GNU Awk.

Upvotes: 2

Related Questions