Tony
Tony

Reputation: 2929

Help with duplicating rows based on a field using awk

I have the following data set with the 3rd field consists of 0's and 1's

Input 

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

I wish to expand the data set to the following format

  1. Duplicate each row based on the 2nd field and

  2. Replace only the "new" 1's (obtain after duplication) in the 3rd field by 0

How can I do this with AWK?

Thanks

Output 
1 2 1
1 2 0
2 4 0
2 4 0
2 4 0
2 4 0
3 3 1
3 3 0
3 3 0
4 1 1

Upvotes: 1

Views: 241

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360733

awk '{print; $3=0; for (i=1; i<$2; i++) print}' inputfile

If you want to actually skip records with a zero in the second field (as your example seems to show):

awk '{if ($2>0) print; $3=0; for (i=1; i<$2; i++) print}' inputfile

Upvotes: 2

Related Questions