Ben Allen
Ben Allen

Reputation: 77

Duplicate number in 2nd row, n number of times, where n is the number in the first row

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

2
3
4

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

3
3

I've done something similar in awk but can't seem to figure out this specific example.

Upvotes: 1

Views: 63

Answers (2)

karakfa
karakfa

Reputation: 67507

just for fun

 read c d < <(head -2 file) | yes $d | head -n $c

extract first two rows, assign to c and d; repeat $d forever but get first $c rows.

Upvotes: 0

John1024
John1024

Reputation: 113864

$ awk 'NR==1{n=$1;} NR==2{for (i=1;i<=n;i++) print; exit;}' file
3
3

How it works

  • NR==1{n=$1;}

    When we reach the first row, save the number in variable n.

  • NR==2{for (i=1;i<=n;i++) print; exit;}

    When we reach the second row, print it n times and exit.

Upvotes: 2

Related Questions