Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: repeat character a variable number of times

Per the questions and ruminations in:

https://unix.stackexchange.com/questions/188658/writing-a-character-n-times-using-the-printf-command

and

How can I repeat a character in bash?

I would like to learn how one might go about parameterizing the repeat value for a character/string. For example, the followings works spiffingly:

printf "   ,\n%0.s" {1..5}

However, if I wanted to parameterize '5', say:

num=5

I cannot seem to get the expansion correct to make this work. For instance:

printf "   ,\n%0.s" {1..$((num))}

fails.

Any thoughts/ideas would be most welcome - I reckon there's a way to do this without having to resort to perl or awk so just curious if poss.

Thanks!

like image 201
Kid Codester Avatar asked May 01 '18 14:05

Kid Codester


2 Answers

You can use seq

num=20;
printf '\n%.0s' $(seq $num)
like image 172
xvan Avatar answered Sep 30 '22 06:09

xvan


If you can build the command as a string -- with all the parameter expansion you want -- then you can evaluate it. This prints X num times:

num=10
eval $(echo printf '"X%0.s"' {1..$num})
like image 25
Rob Davis Avatar answered Sep 30 '22 06:09

Rob Davis