hihihs
hihihs

Reputation: 31

How to use one single command line to show the highest value in the third field

I have a text file named file1. It contains three column of data.
How to use one single command line to show the highest value in the third field?

111 222 333
555 222 222
444 111 212
222 111 111

It tried the following command:

cut -f3 file1 | sort -r 

Upvotes: 2

Views: 82

Answers (4)

Jahid
Jahid

Reputation: 22428

This will do:

cut -d ' ' -f3 file1 |sort -n |tail -1

cut field 3 with space () as delimiter, sort them numerically (-n flag), then take the last entry.

Upvotes: 0

Gunstick
Gunstick

Reputation: 1042

awk '{print $3}' | sort | tail -1

or

sort -rk 3 | awk '{print $3;exit}'

or

awk '$3>a{a=$3}END{print a}'

Upvotes: 1

sjsam
sjsam

Reputation: 21965

Had the objective been to print the sorted values in the descending order, I would do something like this

awk 'NR==FNR{a[$3];next}
      END{asorti(a);
      printf "Sorted values from col3\n";
      while(NR>0){           #NR or the Number of Records comes handy here
      printf "%d\n",a[NR--]  #awk supports post-fix operations using --,++
      }
   }' yourfile

Output:

Sorted values from col3
333
222
212
111

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

I would use awk:

awk '{m=$3>m?$3:m}END{print m}' file

Btw, about the command line you tried, it should be:

cut -d' ' -f3 file | sort -nr | head -n1
       |                         |
       |                         +------------ pipe to head to get just the max
       |
       +---------- cut needs a delimiter

Upvotes: 4

Related Questions