Find Max Value in Column and Print Record – Shell Scripting Guide

scriptingshellshell-script

How to find the max value from the column 1 and echo the respective path location from a file which contains n number of records.

$ cat version.log
112030  /opt/oracle/app/oracle/product/11.2.0
121010  /opt/oracle/app/oracle/product/12.1.0

Expected output:

/opt/oracle/app/oracle/product/12.1.0

Best Answer

This should work:

awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print want} ' version.log

The -v max=0 sets the variable max to 0, then, for each line, the first field is compared to the current value of max. If it is greater, max is set to the value of the 1st field and want is set to the current line. When the program has processed the entire file, the current value of want is printed.

Edit

I did not test the awk solution earlier and it was really my bad to have provided it. Anyways, the edited version of the answer should work (Thanks to terdon for fixing it) and I tested the below as well.

sort -nrk1,1 filename | head -1 | cut -d ' ' -f3

I am sorting on the first field where,

  • -n specifies numerical sort.
  • -r specifies reverse the sort result.
  • -k1,1 specifies first field for the sorting to occur.

Now, after the sorting I am piping the output and just getting the first result which will give me the numerically highest value of column1 in the result.

Now, I finally pipe it to cut with the delimiter specified as space and printing the -f3 which is the intended output.

Testing

cat filename
112030   /opt/oracle/app/oracle/product/11.2.0
121010   /opt/oracle/app/oracle/product/12.1.0
2312     /hello/some/other/path
3423232  /this/is/really/big/number
342      /ok/not/the/maximum/number
9999899  /Max/number
9767     /average/number

Now, after I run the above command for the input as above, I get the output as,

/Max/number
Related Question