How can I conditionally add a field appearance using awk?

I have a file that looks like this:

Level,Member
HIGH,John
HIGH,John
HIGH,Paul
HIGH,George
REG,George
REG,George
REG,George
REG,John
REG,Paul
REG,Paul
REG,Ringo

If I want to add the amount of data appearing in the second column, this works fine:

awk 'BEGIN{ FS=OFS="," }{ $0=$0 OFS (++a[$2]) }1' file

But it’s hard for me to figure out how to add an if / else statement so that I can conditionally count by level so that my output looks like this:

Level,Member,1
HIGH,George,1
HIGH,John,1
HIGH,John,2
HIGH,Paul,1
REG,George,1
REG,George,2
REG,George,3
REG,John,1
REG,Paul,1
REG,Paul,2
REG,Ringo,1 

Note that the countdown starts when the level changes from HIGH to REG. The file is already sorted by level and then by member.

+4
source share
3 answers

Your team was already good. I just changed the associative array key a []:

awk 'BEGIN{ FS=OFS="," }{ $0=$0 OFS (++a[$2$1]) }1' file

or

awk 'BEGIN{ FS=OFS="," }{ $0=$0 OFS (++a[$0]) }1' file
+1
source

or simply..

$ awk '{$0=$0","++a[$0]}1' file
Level,Member,1
HIGH,John,1
HIGH,John,2
HIGH,Paul,1
HIGH,George,1
REG,George,1
REG,George,2
REG,George,3
REG,John,1
REG,Paul,1
REG,Paul,2
REG,Ringo,1
+2
source

:

awk '{print $0","(++c[$0])}'
+2

Source: https://habr.com/ru/post/1694368/