Need help in awk: running a loop with one column and segregate data 4 each uniq value in that field

Hi All,

I have a file like this(having 2 column).

Column 1: like a,b,c....
Column 2: having numbers.

I want to segregate those numbers based on column 1.

Example:

file.

a 5
b 9
b 620
a 710
b 230
a 330
b 1910
a 2020

for each value of column 1, these data required.

greater than 0 and less than 600
greater than 600 and less than 1800
greater than 1800

Output should be like this.

a[0-600] = 2
a[600-1800] = 1
a[above 1800] = 1
b[0-600] = 2
b[600-1800] = 1
b[above 1800] = 1

I can do that with help of for loop, but I want to know, how to do this with just AWK.

for i in `awk '{print $1}' /home/ABC/gtacMonitoring/monLogs/ngnDurationLog|sort|uniq`
do
echo "$i"
awk -v var="$i" '{if($1==var && ($2 > 0 && $2 < 600)) {print "[Between 00-10 min]:"} else if($1==var && ($2 >= 600 && $2 < 1800)) {print "[Between 10-30 min]:"} else if($1==var && $2 >= 1800) {print "[More than  30 min]:"}}' /home/ABC/gtacMonitoring/monLogs/ngnDurationLog|sort|uniq -c|awk -F"[" '{print "["$2,$1}'
echo
done

You're close. Did you consider deploying arrays?
Will negative values be present in field (COL) 2?

Hi Rudi,

Thank you for response.

I understand that it can be done with array, but not able to use logic with same.
Column 2 will not contain any negative value, in fact it will be always greater than 0.

Regards,
Raza Ali

Try

awk -v THRSTR="600 1800" '
BEGIN   {n = split (THRSTR, THR)
        }
        {for (i=1; i<=n; i++)   {if ($2 <= THR) break
                                }
         RES[$1,i]++
        }

END     {for (r in RES) {split (r, T, SUBSEP)
                         print T[1], "[" THR[T[2]-1] "-" THR[T[2]] "] = " RES[r]
                        }
        }
'   file

a [-600] = 2
a [600-1800] = 1
a [1800-] = 1
b [-600] = 2
b [600-1800] = 1
b [1800-] = 1

Your request leaves open where to count the exact boundary values - here I count them to the lower interval, i.e. 600 goes to 0 - 600, 601 to 600 - 1800.

EDIT: Oh, I see that your code snippet handles it vice versa. Exercise for you to adapt the proposal . . .

1 Like

Hi Rudi,

Thank you for providing the solution.

Regards,
Raza Ali