Ben Allen
Ben Allen

Reputation: 77

Duplicate each number in a row n times, where n is the number in the row

I have text files that each have a single column of numbers:

2
3
4

I want to duplicate each line n times, where n is the number in the row, so the output looks like this:

2
2
3
3
3
4
4
4
4

The only examples I have found used a fixed number of n.

I thought sed might be good to read each line, but I haven't been able to figure out how to tell sed to use the number in each line as the value for the of times the line should be duplicated.

Upvotes: 0

Views: 91

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754110

'Tis trivial in awk:

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

Or, equivalently:

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

Note that the code tests against $1 rather than $0, but prints $0 rather than $1. This allows you to have an input such as:

12 Lords a-leaping
11 Ladies dancing
10 Drummers drumming
9 Pipers piping
8 Maids a-milking
7 Swans a-swimming
6 Geese a-laying
5 Gold rings
4 Calling birds
3 French hens
2 Turtle doves
1 Partridge in a pear tree

and you'll get rather copious output repeating the lines as often as the first number in the line dictates.

Upvotes: 3

Related Questions