Search code examples
awksedgrepuniq

Fillter grep results by range and display in column


I have extract this data with grep from my log stats, data and value:

Apr-1 -4
Apr-1 -2
Apr-1 -5
Apr-1 5
Apr-1 95
Apr-2 -4
Apr-2 -6
Apr-2 -8
Apr-2 9

I need to display count by range: <=4 , from >4 to <8 and >= 8 and then display group by day in column. like this:

Day      <=4     >4 & <8    >= 8
--------------------------------
Apr-1     3         1         1
Apr-2     3         0         1

I did some tests and research with awk uniq... but I got no results

Thanks!


Solution

  • awk '
        {days[$1] = 1}
        $2 <= 4 {a[$1]++} 
        4 < $2 && $2 < 8 {b[$1]++} 
        $2 >= 8 {c[$1]++} 
        END {
            OFS="\t"; 
            print "Day","<=4", "4<x<8", ">=8"; 
            PROCINFO["sorted_in"] = "@ind_str_asc"; 
            for (day in days) 
                print day, a[day]+0, b[day]+0, c[day]+0
        }
    ' <<END | column -t 
    Apr-1 -4
    Apr-1 -2
    Apr-1 -5
    Apr-1 5
    Apr-1 95
    Apr-2 -4
    Apr-2 -6
    Apr-2 -8
    Apr-2 9
    END
    
    Day    <=4  4<x<8  >=8
    Apr-1  3    1      1
    Apr-2  3    0      1
    

    The reason for adding zero to the values when printing is that empty values (such as Apr-2 4<x<8) will show up as empty strings. When forced into a numeric context by adding zero, they show up as 0.