Retrieving the maximum and minimum value using awk

How to find the maximum and minimum value from the table below using the awk command.

 20 90 60 30 55 75 80 85 10 15 99 95 55 95 70 20 9 35 85 75 

I need output like max value=99 and min=9

+4
source share
3 answers

with gnu awk:

 awk '{for(x=1;x<=NF;x++)a[++y]=$x}END{c=asort(a);print "min:",a[1];print "max:",a[c]}' 

output:

 min: 9 max: 99 

without awk:

 xargs -n1|sort -n|head or tail -1 

eg.

min:

 kent$ echo "20 90 60 30 55 75 80 85 10 15 99 95 55 95 70 20 9 35 85 75"|xargs -n1|sort -n|head -1 9 

tach:

 kent$ echo "20 90 60 30 55 75 80 85 10 15 99 95 55 95 70 20 9 35 85 75"|xargs -n1|sort -n|tail -1 99 

you can of course xargs -n1|sort -n , then go to awk to select the first and last and print in one shot.

+8
source
 awk ' NR == 1 { min=max=$1 } { for (i=1;i<=NF;i++) { min = (min < $i ? min : $i) max = (max > $i ? max : $i) } } END { printf "min value = %s\n", (min == "" ? "NaN" : min) printf "max value = %s\n", (max == "" ? "NaN" : max) } ' file 

The test leading to "NaN" is designed to place empty input files.

+4
source

If you have GNU awk :

 # using array awk '{x[NR]=$1}END{asort(x);print "max="x[NR],"min="x[1]}' RS=' +|\n' file max=99 min=9 # No array awk 'NR==1{m=n=$1}{$1>m?m=$1:m;$1<n?n=$1:n}END{print "max="m,"min="n}' RS=' +|\n' file max=99 min=9 
+4
source

Source: https://habr.com/ru/post/1491129/


All Articles