Skip to content
Advertisement

Print min and max with awk

Why wont this awk script work, where I want to print the min and max of an input by just reading the data once. I would also like to initialize the min and max variable with the first value of the data.

Say I have a file

a 14
a 34
a 234
a 2345
a 1
a 24

I am using awk to print the min and max with:

cat test.txt | awk 'BEGIN {min=$2; max=$2} {if ($2 < min) {min=$2}; if ($2 > max) {max=$2} } END {print "min: " min "max: " max}'

But I am getting a result of:

min: max: 2345

I dont understand why min is set to blank?

Advertisement

Answer

The BEGIN {} block is processed before the first line so $2 is undefined.

$ cat file
a 14
a 34
a 234
a 2345
a 1
a 24
$ awk 'NR == 1  { min = max = $2; next }
       $2 > max { max = $2 }
       $2 < min { min = $2 }
       END      { print "min: " min ", max: " max }' file
min: 1, max: 2345
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement