This awk single-line engine works for me:
[ ghoti@pc ~]$ awk 'prev!=$2{first=0;prev=$2} {$1=first;first++} 1' input.txt 0 1 a 1 1 b 2 1 d 3 1 d 0 2 g 1 2 a 0 3 b 1 3 d 0 4 d 0 5 g 1 5 g
Separate the script and see what it does.
prev!=$2 {first=0;prev=$2} - This is what your counter resets. Since the initial state of prev empty, we reset in the first line of input, which is good.{$1=first;first++} - for each line set the first field, then add the variable that we use to set the first field.1 is awk short-hand for "print the line". This is really a condition, which is always evaluated as "true", and when a pair of conditions / operators is not in the instruction, the operator defaults to "print".
Pretty simple indeed.
Of course, one conclusion is that when you change the value of any field in awk, it overwrites the string using any field delimiters, which by default are just space. If you want to configure this, you can set the OFS variable:
[ ghoti@pc ~]$ awk -vOFS=" " 'p!=$2{f=0;p=$2}{$1=f;f++}1' input.txt | head -2 0 1 a 1 1 b
Salt to taste.
ghoti source share