5

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!

Andreas Louv
  • 44,338
  • 13
  • 91
  • 116
Kid Codester
  • 75
  • 1
  • 4

3 Answers3

6

You can use seq

num=20;
printf '\n%.0s' $(seq $num)
xvan
  • 4,281
  • 1
  • 18
  • 35
  • If one resorts to an external command then AWK would be more portable, as `seq` is part of GNU coreutils. – Andreas Louv May 01 '18 at 14:21
  • Thank you very much for this. Per the other comment, I'd like to stick to something as portable as possible, hence my selection of the eval solution but I appreciate this suggestion and its workaround to the dangers of using eval. – Kid Codester May 01 '18 at 14:46
3

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})
Rob Davis
  • 15,197
  • 5
  • 43
  • 49
0

A slighly different approach

$ repeat() {
    local str=$1 n=$2 spaces
    printf -v spaces "%*s" $n " "     # create a string of spaces $n chars long
    printf "%s" "${spaces// /$str}"   # substitute each space with the requested string
}
$ repeat '!' 10
!!!!!!!!!!                     # <= no newline
$ repeat $'   ,\n' 5
   ,
   ,
   ,
   ,
   ,
glenn jackman
  • 223,850
  • 36
  • 205
  • 328