5

Per the questions and ruminations in:

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!

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Kid Codester
  • 75
  • 1
  • 4

3 Answers3

6

You can use seq

num=20;
printf '\n%.0s' $(seq $num)
xvan
  • 4,554
  • 1
  • 22
  • 37
  • 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,597
  • 5
  • 45
  • 49
1

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
  • 238,783
  • 38
  • 220
  • 352