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// /+}"
++++++++++

4 comments:

I_LOVE_FDM said...

Hi,

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...

@I_LOVE_FDM

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

© Jadu Saikia www.UNIXCL.com