This question already has an answer here:

I would like to have the following sequence: OW HW1 HW2 being repeated in an output file 3000 times such as:

OW
HW1
HW2
.
.
.
OW
HW1
HW2

I believe I can, by using bash, set the OW, HW1 and HW2 as independent variable and then make a do loop 3000 times and print the values in the output file.

marked as duplicate by Goro, G-Man, Isaac, Anthony Geoghegan, schily 4 hours ago

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

You can use this printf trick with a zero-length string specifier %.0s and brace expansion:

printf '%.0sOW\nHW1\nHW2\n' {1..3000} > newfile
  • super this works just perfect!!!! – Dimitris Mintis Oct 12 at 12:19
  • 1
    This is a good (brief) solution for small inputs, but very inefficient when the number of repetitions is large. Better to use awk in that case, e.g. awk 'BEGIN{for(i=1;i<=3000;i++)print"OW\nHW1\nHW2"}'>file – user000001 Oct 12 at 17:07
  • 1
    @user000001 So it's the right tool for the job in this post... – user1717828 Oct 12 at 19:43

It can be easily done with Perl:

perl -e'print "OW\n\HW1\nHW2\n"x3000'

If use for in cycle:

for i in $(seq 1 3000) ; do echo -e "OW\nHW1\nHW2"; done

or use echo 3x

for i in $(seq 1 3000) ; do echo OW; echo HW1; echo HW2; done
  • This is great, but then how do I print this sequence 3000 times in the file? – Dimitris Mintis Oct 12 at 12:08
  • Use redirection: for i in $(seq 1 3000) ; do echo -e "OW\nHW1\nHW2" >>file.txt ; done – schweik Oct 12 at 12:18
  • I like this. Most clear answer in my opinion. OOC, is seq 3000 the same as seq 1 3000? – user1717828 Oct 12 at 19:44

You could simply use yes and head to generate this sequence 3000 times.

yes $'OW\nHW1\nHW2' | head -9000

Here you need the 9000 because you have 3 lines and you want those 3 lines 3000 times.

If your shell offers "brace expansion", try

echo $'\nOW\nHW1\nHW2\n'{1..3000}$'\n' | grep -Ev "^( |[0-9])*$"
OW
HW1
HW2
OW
HW1
HW2
OW
HW1
HW2
.
.
.

and redirect to a file if happy with the result.

you can use a while loop like here: http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_02.html

An example:

COUNTER=0; while [ $COUNTER -lt 3 ]; do echo "$COUNTER" && COUNTER=$((COUNTER+1)); done

Don't forget to reset the COUNTER every time you want to run this.

New contributor
Timo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Python3 solution

python3 -c 'print("OW\nHW1\nHW2\n"*3000, end="")' 

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