AWK. how to add the same sequential number between the separator?

Viewed 48

I have a file as follows:

Lisa with a client ID
####
Mike with a boss ID
Tim with a boss ID
Joe with a boss ID
####
Susan with a sales ID
Jenny with a sales ID
####

And I would like the output as:

Group1,Lisa with a client ID
Group2,Mike with a boss ID
Group2,Tim with a boss ID
Group2,Joe with a boss ID
Group3,Susan with a sales ID
Group3,Jenny with a sales ID

I have tried the following command:

awk 'BEGIN{ RS="####"}!$0{ next }{printf($0="Group"++i","$0)}' file.txt

But the output seems just replace #### with a sequential number, like:

Group1,Lisa with a client ID
Group2,
Mike with a boss ID
Tim with a boss ID
Joe with a boss ID
Group3,
Susan with a sales ID
Jenny with a sales ID
Group4

I was wondering how to add the same sequential number to the beginning of the lines between the separator? Many thanks!!

1 Answers

Count how many times #### occurs and output the result in each row. Start counting with 1.

awk 'BEGIN{c=1} /^####/{c++; next} {print "Group" c "," $0}' file

Output:

Group1,Lisa with a client ID
Group2,Mike with a boss ID
Group2,Tim with a boss ID
Group2,Joe with a boss ID
Group3,Susan with a sales ID
Group3,Jenny with a sales ID
Related