Search code examples
linuxawkmax

print all maximum values using awk


I'm trying to print all maximum values

so, if the text looks like

'''

name1 job1 9500.
name2 job2 9500.
name3 job3 4500.

'''

I want to print it like

'''

job: job1, sal: 9500
job: job2, sal: 9500

''''

so far, my code is

'''

     BEGIN {a=0}

     {if ($3> a)
     max=$3;
     output=$2
        }

  END{
    print "job: ", output, "sal:", max}

'''

and the output I'm getting is

'''

job: job2, sal: 9500 

'''


Solution

  • One way might be keeping track of the maximum number, and if you have a number that is higher then store that number.

    If it is the same amount as the current number, then keep track of those lines (field 2 and field 3) in an array, and at the end print them.

    awk '
    {
      if ($3 > max) {
        max = $3
        i = 0;
        lines[++i] = $2 OFS $3
        next;
        }
      if ($3 == max) lines[++i] = $2 OFS $3
    }
    END {
      for (j=1;j<=i; j++) print lines[j]
    }' file
    

    Output

    job1 9500
    job2 9500