Search code examples
linuxbashubuntu-18.04

Repeat each line multiple times by using Linux


I have 1 file with some data. Like

my_file:

1 3 a
4 8 b
9 14 c

output_file:

a
a
b
b
b
b
c
c
c
c
c

I am trying to repeat each line multiple times(3-1 = 2 , 8-4 =4 , 14-9 = 5). I am tying this command:

while read i; do seq 1 2| xargs -i -- echo $i;done < my_file.txt 

But it is repeating 2 times for all lines. I want to repeat each line N times. Is it possible? If it is will you please give me some suggestions.

Thanks in advance.


Solution

  • In case is an option:

    perl -ne '@A=split;print "$A[2]\n" x ($A[1]-$A[0])' my_file.txt
    

    For each line, it splits the line on whitespace and @A is the array holding that result.

    It then prints the third element in the array ($A[2]) + a newline, repeated (the x) the number of times you have if you take the value in column 2 minus the value in column 1.