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

6 comments:

MysteriouslyMe 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! :)

Unknown said...

@I_LOVE_FDM

Something like ?

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

$ echo $var
++++++++++

MysteriouslyMe 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'

Unknown said...

c='-'
knt=5

# Method-1: Dc
dc -e "
[q]sq
[d0=q1-rdnrlax]sa
[$c]${knt}d0=q
lax[]p
"
# Note: characters ']' '[' cannot be used with the above method.


# Method-2: Perl
perl -sle '$knt and print $c x $knt' -- -c="$c" -knt="$knt"


# Method-3: Bash
case $knt in 0 ) exit;; esac
set -- "$c" ''
while :; do
v=$1; shift
case $# in "$knt" ) break;; esac
set -- "$c$v" "$1" ${1+"$@"}
done
printf '%s\n' "$v"

© Jadu Saikia www.UNIXCL.com