How to use printf to print a character multiple times?
I know this is old but the width modifier can be used e.g.
l = some_value
print gensub(/ /, "-", "g", sprintf("%*s", l, ""))
will print a variable number of - depending on the value of l
This was GNU Awk 3.1.8
I do not believe this is possible with awk's printf, as there is also no way to do this just with printf in C and C++.
With awk, I think the most reasonable option is using a loop like you have. If for some reason performance is vital and awk is creating a bottleneck, the following will speed things up:
awk 'BEGIN {s=sprintf("%5s","");gsub(/ /,"-",s);print s}'
This command will run logarithmically faster[1] Though, it won't cause a noticeable difference in performance unless you're planning on printing a character many times. (Printing a character 1,000,000 times will be about 13x faster.)
Also, if you want a one-liner and are using gawk, even though it's the slowest of the bunch:
gawk 'BEGIN {print gensub(/ /,"-","g",sprintf("%5s",""));}'
[1] While the sprintf/gsub command should always be faster than using a loop, I'm not sure if all versions of awk will behave the same as mine. I also do not understand why the while-loop awk command would have a time complexity of O(n*log(n)), but it does on my system.