Indexing each repeating pattern of rows in a column using awk/sed

Hello All,

I have data like this in a column.

0
1
2
3
0
3
4
5
6
0
1
2
3
etc.

where 0 identifies the start of a pattern in my data.
So I need the output like below using either awk/sed.

0  1
1  1
2  1
3  1
0  2
3  2
4  2
5  2
6  2
0  3
1  3
2  3
3  3

Basically indexing every repeating pattern and add additional column with that index number.

Thanks in advance
Sidda

As I am sure you already know, sed doesn't do arithmetic...
Try:

awk '
$1 == 0{ pat++ }
{ printf("%s  %d\n", $0, pat) }
' data

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

1 Like

Or

awk '{printf "%s  %d\n", $0, p+=$1==0}' file
0  1
1  1
2  1
3  1
0  2
3  2
4  2
5  2
6  2
0  3
1  3
2  3
3  3

or even

awk '{print $0, p+=$1==0}' file
1 Like