writing a string made up of a smaller string repeated many times
Wednesday, 4 February 2026 05:07 pmThis was an interesting diversion today. I needed a way to construct a long string from a smaller one repeated many times, so I tried a few ways of my own devising and found many more on the net. There were some surprising ways to do this, but the really big surprises came when I decided to time them so as to work out which is the fastest. The winner is
NOTE: The time values I give below are the times to make a string repeating "test" 100,000 times.
Here is my list of solutions:
A tricky way to use
A slightly different way to
An
simple
two simple
simple c-style loop
a weird one
using awk for part
awk only
using sed for part
or
or
yes. That really surprised me. The next two fastest are sed -E (extended regex) and plain sed.NOTE: The time values I give below are the times to make a string repeating "test" 100,000 times.
Here is my list of solutions:
yes is a command that endlessly prints out a stringyes "test" | head -n 10 | tr "\n" " " ; echo0.044 seconds
A tricky way to use
printfprintf 'test %.0s' {1..10} ; echo0.190 secondsprintf to a variableprintf -v testvar 'test %.0s' {1..10}0.169 secondsA slightly different way to
printf to a variableprintf -v testvar '%s ' test$_{1..10}0.194 secondsAn
echo {} hack.It requires that $nothing1 $nothing2 $nothing3 ... be non-existent variables.echo test$nothing{1..10}0.217 secondssimple
{} sequence loopfor i in {1..10} ; do echo -n "test " ; done ; echo1.482 secondstwo simple
seq loopsfor i in $(seq 10) ; do echo -n "test " ; done ; echo1.617 seconds
for i in `seq 10` ; do echo -n "test " ; done ; echo1.367 seconds
simple c-style loop
n=10 ; for (( c=1; c<=n; c++)) ; do echo -n "test " ; done ; echo2.130 seconds
a weird one
echo 'test'{,,,,,,,,,}using awk for part
seq 10 | awk '{printf "test "}'; echo0.769 secondsawk only
awk 'BEGIN{for (n=0; n<10; n++) printf "test "; print ""}'0.880 secondsusing sed for part
seq 10 | sed -E 's/.+/test/' | tr '\n' ' ' ; echo0.089 seconds
or
seq 10 | sed 's/.*/test/' | tr '\n' ' ' ; echo0.096 seconds
or
seq 10 | sed -z 's/[^\n]*\n/test/g' ; echo0.173 seconds