There are several questions about how to duplicate lines, I want to automatically duplicate each line the specific number of times as found in field one of a file. I have a large file with two fields, field one is a number, field two is the information in question, like this.

12     AAA
18     BBB
25     CCC
33     DDD

I would to duplicate each line so it is represented the same number of times as the number in field one. So, I want 12 lines that say "12 AAA" and so on.

I know that I can manually paste each line x number of times in vim (copy and then "12p") but this seems onerous for a large file. Does anyone know a script that can do it automatically?


Using GNU awk:

#!/usr/bin/gawk -f
    for (c=strtonum($1) ; c ; c--) 
  • A simple $1+0 should also force the integer conversion right?
    – Inian
    Sep 25 '18 at 16:04
  • @Inian Provided the number is in decimal, it seems it doesn't even need the +0. If the number is in eg. hex, $1+0 gives no repeats, and $1 gives infinite.
    – JigglyNaga
    Sep 25 '18 at 16:18

With awk same as JigglyNaga's answer:

awk '{ c=0; while ($1>c++) print }' infile

An alternative awk solution:

<infile awk ' i=$1 { while(i--) print }' 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.