tags:

views:

51

answers:

7

This seems like a simple problem but I couldnt find a ready solution. I need to generate a string of characters "."s as a variable.

ie, IN my bash script, I need to generate a string of length 15 ...............

I need to do so variably. I tried using this as a base (from: http://www.unix.com/shell-programming-scripting/46584-repeat-character-printf.html)

for i in {1..100};do printf "%s" "#";done;printf "\n"

But how do i get the 100 to be a vairbale?

A: 

I don't know if I got the question.. maybe you can do it like this

function myPrint { for i in `seq 1 $2`; do echo -n $1; done }; myPrint <char> <number>
Francesco
Not exactly... I want the 100 to be a variable. I modified the above to be this:function myPrint { for i in seq 1 $1; do echo -n '.'; done };BUT I already have a $1 coming in from the command line. How can I use this argument?
RubiCon10
mh I didn't understand.. do you want to use in this function as first argument the first argument of the script that contains the function? if this just try "myPrint $1" in your script..
Francesco
A: 

Just put your code into $( )

myvar=$(for i in {1..100};do printf "%s" "#";done;printf "\n")
Till
+2  A: 

On most systems, you could get away with a simple

N=100
myvar=`perl -e "print '.' x $N;"`
Christopher Creutzig
A: 

The solution without loops:

N=100
myvar=`seq 1 $N | sed 's/.*/./' | tr -d '\n'`
Aleksey Otrubennikov
+1  A: 
len=100 ch='#'
printf '%*s' "$len" ' ' | tr ' ' "$ch"
Chris Johnsen
A: 

When I have to create a string that contains $x repetitions of a known character with $x below a constant value, I use this idiom:

base='....................'
# 0 <= $x <= ${#base}
x=5
expr "x$base" : "x\(.\{$x\}\)"    # Will output '\n' too

Output:

.....
dolmen
A: 

You can use C-style for loops in Bash:

num=100
string=$(for ((i=1; i<=$num; i++));do printf "%s" "#";done;printf "\n")

Or without a loop, using printf without using any externals such as sed or tr:

num=100
printf -v string "%*s" $num ' ' '' $'\n'
string=${string// /#}
Dennis Williamson