Find the answer to your Linux question:
Results 1 to 4 of 4
Hi all, I have this: AA COLOR 6 GREEN BB COLOR 3 BLUE CC COLOR 4 PINK DD COLOR 1 RED EE COLOR 9 MAGENTA How can I have awk ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Feb 2013
    Posts
    37

    Print line that contains highest value in column


    Hi all,

    I have this:

    AA COLOR 6 GREEN
    BB COLOR 3 BLUE
    CC COLOR 4 PINK
    DD COLOR 1 RED
    EE COLOR 9 MAGENTA

    How can I have awk printing the line containing the highest value in column 3?

    EE COLOR 9 MAGENTA


    My code:

    awk 'BEGIN {max = 0} {if ($3 > max ) max = $3} END {print max}' file.txt

    prints just the value, not the entire line.

    As an alternative I was thinking of a second conditional in the same code:

    "if column three matches "max" then print all columns" but not sure if this makes any sense.

    Any ideas?

  2. #2
    Linux Newbie
    Join Date
    Nov 2012
    Posts
    224
    you really don't think hard enough
    Code:
    awk 'BEGIN {max = 0} {if ($3 > max ){max = $3; line2keep=$0} END {print line2keep}' file.txt

  3. #3
    Just Joined!
    Join Date
    Feb 2013
    Posts
    37
    Quote Originally Posted by watael View Post
    you really don't think hard enough
    Code:
    awk 'BEGIN {max = 0} {if ($3 > max ){max = $3; line2keep=$0} END {print line2keep}' file.txt
    Are you sure your code is right?

    A quick test over this:

    AA COLOR 6 GREEN
    BB COLOR 3 BLUE
    CC COLOR 4 PINK
    EE COLOR 9 MAGENTA
    DD COLOR 1 RED


    renders this:

    DD COLOR 1 RED

    And that line is not the one with the highest value in column #3

  4. #4
    Just Joined!
    Join Date
    May 2013
    Posts
    1
    This works fine for me, although there's a syntax error in the awk line (missing } before END, displayed bold below):

    Code:
    awk 'BEGIN {max = 0} {if ($3 > max ){max = $3; line2keep=$0}} END {print line2keep}' file.txt
    Log from my console:

    Code:
    [poljpocket@fedora18 ~]$ cat > file.txt << EOF
    > AA COLOR 6 GREEN
    > BB COLOR 3 BLUE
    > CC COLOR 4 PINK
    > EE COLOR 9 MAGENTA
    > DD COLOR 1 RED
    > EOF
    [poljpocket@fedora18 ~]$ awk 'BEGIN {max = 0} {if ($3 > max ){max = $3; line2keep=$0}} END {print line2keep}' file.txt
    EE COLOR 9 MAGENTA
    [poljpocket@fedora18 ~]$

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •