1

In Unix, I am trying to find a command that would find the maximum value in Column3 and print the corresponding values from Column2 and Column1 (but not from Column3) in a new file.

 Column1     Column2     Column3
   A          1          25
   B          2          6
   C          3          2
   D          4          16
   E          5          10

What should be the Unix command? Should I use grep or awk or datamash?

3

I would use awk. Assuming that the data is formatted exactly as per your sample data, the following will produce the desired output:

awk -v MAX=0 '{ if(NR>1 && $3>MAX){WANT1=$1; WANT2=$2; MAX=$3}} END{print WANT1, WANT2}' infile > outfile
1

Assuming that your data is formatted exactly as stated by you (this goes especially for the 3rd column, numbers all left aligned) and that this data is provided by cating a file, you could try this command:

*input generating command* | sort -nrk3 | awk '{print $1 " " $2}' > output_file

In case your data is provided by some other command or source, change cat to that other command. For more information see this post which I basically just tailored to your needs.

Edit:

I changed the above command slighty as there's no need to tell sort to start from column 3 character 1, since sort always treats a blank as a separator. One can of course give the input file straight to sort as well, as a user pointed out. If also the headers are part of your data, change the above command to:

*input generating command* | sort -nrk3 | awk '{if (NR>1) print $1 " " $2}' > output_file
5
  • UUOC - Useless Use Of Cat.
    – fpmurphy
    Nov 27 '19 at 18:03
  • Useless comment. I can't know where the users data comes from, so I just provided a possible example Nov 27 '19 at 18:04
  • That is a oood point!
    – fpmurphy
    Nov 27 '19 at 18:17
  • BTW, your answer prints ALL rows including the header.
    – fpmurphy
    Nov 27 '19 at 18:22
  • Thanks for the heads-up. Nov 27 '19 at 18:28
0
awk '{if(NF>2 && $3>M){M=$3;print $1,$2} }' file1 | tail -1 > file2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.