Repeat each line in a text n times
Solution 1
It can easily be done in perl
:
perl -ne 'print $_ x 3' file
the above oneliner output:
$ perl -ne 'print $_ x 3' file
888
888
888
924
924
924
873
873
873
1374
1374
1374
Just change the sample value for your needs.
An awk
solution:
awk '{for (i = 1; i <= 3; i++) print $1}' file
To fix your bash script I would use the following snippet instead:
#!/bin/bash
while read line
do
for i in {1..3}; do echo $line; done
done < ./file
Solution 2
There is a nice trick to print a string repeatedly:
$ printf "%0.s-" {1..10}
----------
Based on that, we can loop through the file and print the line as many times as we indicate in the brace expression:
while IFS= read -r line
do
printf "%0.s$line\n" {1..3}
done < file
Test
change this number as you wish
v
$ while IFS= read -r line; do printf "%0.s$line\n" {1..3}; done < a
888
888
888
924
924
924
873
873
873
1374
1374
1374
Although my preference would be to use an awk
like this, very similar to what others posted before (nice answers by the way):
awk -v tot=3 '{for (i=1; i<=tot; i++) print}' file
Solution 3
You could simply do this through sed.
$ sed 's/\(.*\)/\1\n\1\n\1/g' file
888
888
888
924
924
924
873
873
873
1374
1374
1374
Related videos on Youtube
Comments
-
efrem over 1 year
I have a file that looks like this
888 924 873 1374 .....
The dots indicate that I have many more string, around 3000. I want repeat each string n time, to have something like this;
888 888 888 924 924 924 873 873 873 ....
I tried to write a small bash code:
#! bin/bash while IFS= read -r line do awk 'NR==line' awk 'NR==line' awk 'NR==line' done < /<PATH_TO_FILE>
But I get no results. I thought that this was a quite easy task, but obviously I am missing something. Any advise?
-
choroba about 9 years
perl -ne 'print $_ x 3' file
is even easier. -
Sylvain Pineau about 9 years@choroba: indeed, I tried but forgot that it required spaces around the
x
operator. Thanks. I'm updating the answer. -
efrem about 9 yearsgreat thanks. I would prefer an awk solution, because I know it a bit better and I have to edit the file even more after performing this first step.
-
Sylvain Pineau about 9 years@efrem: I've updated my answer with an
awk
solution -
efrem about 9 yearsworks perfectly, any idea why my code sucked?
-
Sylvain Pineau about 9 years@efrem: It seems that the awk commands were unneeded. See my update