Nolohice
Nolohice

Reputation: 339

copying & pasting a row n times based on corresponding number in a cell within that row

Say I have a csv file with "," as the field separator in this format:

0.051278,1,0,0,4,0,1,2
0.024788,1,7,0,0,0,0,0
0.042316,1,0,0,1,0,0,0

What I want to do is copy and paste each row n times were n is the number in the first column times 100. So the first row would appear 5 times, the second row 2 times, the third row 4 times, and so on.

Desired output:

0.051278,1,0,0,4,0,1,2
0.051278,1,0,0,4,0,1,2
0.051278,1,0,0,4,0,1,2
0.051278,1,0,0,4,0,1,2
0.051278,1,0,0,4,0,1,2
0.024788,1,7,0,0,0,0,0
0.024788,1,7,0,0,0,0,0
0.042316,1,0,0,1,0,0,0
0.042316,1,0,0,1,0,0,0
0.042316,1,0,0,1,0,0,0
0.042316,1,0,0,1,0,0,0

The actual data file has over 2000 rows and the decimal number in the first line ranges anywhere from .03(more decimal places) to .7(more decimal places). Numbers would have to be rounded as you can't copy and paste a row 2.5 times. So, something like .25 would go to .3 and .24 would go to .2

Upvotes: 1

Views: 265

Answers (1)

hek2mgl
hek2mgl

Reputation: 158060

With awk:

awk -F, '{for(i=0;i<$1*100;i++)print}' input.txt

In the above solution 0.0234 and 0.0236 would get print 23 times. Is this what you want?

If you need rounded values, I suggest to use something like this:

awk -F, '{for(i=0;i<int($1*100+.5);i++)print}' input.txt

Thanks Ed Morton!

Upvotes: 4

Related Questions