Sunday, March 8, 2009

Repeat a character in bash scripting

Requirement: Repeat a particular character n number of times and print in a single line.

e.g. Repeat the character '+' 10 times and print the output in a single line.

The solutions:

#Using bash for loop:
$ for((i=1;i<=10;i++));do printf "%s" "+";done;printf "\n"

$ for i in $(seq 10); do echo -n '+'; done

$ for i in {1..10};do printf "%s" "+";done;printf "\n"

#Using bash seq:
$ seq -s "+" 11 | sed 's/[0-9]//g'

#Perl one liner for the same:
$ perl -e 'print "+" x 10,"\n"'

#And using bash printf:
$ printf -v f "%10s" ; printf "%s\n" "${f// /+}"


I_LOVE_FDM said...


Is there any way to pipe or redirect this output to a variable?

Basically, I want to create a string "-------" with a variable number of "-".

Thanks in advanced! :)

Jadu Saikia said...


Something like ?

$ var=$(seq -s "+" 11 | sed 's/[0-9]//g')

$ echo $var

I_LOVE_FDM said...

THANKS!! idk why it didnt work for me, but I found a different way to do what i was trying to do.

***I got an assignment to make a hangman games without using sed or awk. i wastrying to see if i could get a list of already guessed words into one string variable, but that would have make things so complicated!

Unknown said...

My favorite way is

Printf "%${a}s\n" "" | sed -e 's/ /+/g'

I have tested a 5000 and it works

Anirudh said...

Surprisingly the cshell has a construct tailor-made for just this scenario, known as the "repeat" command. usage: repeat count cmd [options of command cmd]

So if we wanted a string of 10 +
% repeat 10 echo -n '+'; echo # display 10 + on terminal
% set result = `repeat 10 echo -n '+'` # store 10 + in variable result

From bash you would invoke as
$ csh -c 'repeat 10 echo -n "+";echo' # display 10 + on terminal
$ result=$(csh -c 'repeat 10 echo -n "+";echo') # store 10 + in variable result

Another way could be via the use of the "yes" command:

$ yes '+' | sed -e 'H;1h;10!d;g;s/\n//g;q'

© Jadu Saikia