Home » Questions » Computers [ Ask a new question ]

Linux command to repeat a string n times

Linux command to repeat a string n times

Is there any built-in Linux command that allows to output a string that is n times an input string??

Asked by: Guest | Views: 43
Total answers/comments: 5
Guest [Entry]

"adrian@Fourier:~$ printf 'HelloWorld\n%.0s' {1..5}
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
adrian@Fourier:~$"
Guest [Entry]

"This can be parameterized and doesn't require a temp variable, FWIW:

printf ""%${N}s"" | sed 's/ /blah/g'

Or, if $N is the size of a bash array:

echo ${ARR[@]/*/blah}"
Guest [Entry]

"Perhaps another way that is more general and useful for you:

adrian@Fourier:~$ n=5
adrian@Fourier:~$ for (( c=1; c<=n; c++)) ; do echo ""HelloWorld"" ; done
HelloWorld
HelloWorld
HelloWorld
HelloWorld
HelloWorld
adrian@Fourier:~$

The bash shell is more powerful than most people think :)"
Guest [Entry]

"Repeat n times, just put n-1 commas between {}:

$ echo 'helloworld'{,,}
helloworld helloworld helloworld

Repeats 'helloworld' twice after the first echo."
Guest [Entry]

"POSIX AWK:

#!/usr/bin/awk -f
function str_repeat(s1, n1) {
s2 = """"
for (n2 = 1; n2 <= n1; n2++) {
s2 = s2 s1
}
return s2
}
BEGIN {
s3 = str_repeat(""Sun"", 5)
print s3
}

Or PHP:

<?php
$s3 = str_repeat('Sun', 5);
echo $s3, ""\n"";"