[Home]
HomePage RecentChanges Frequently Asked Questions

RepeatAString

Sometimes it is useful to have something like Perl's 'x' operator, which repeats a string N times. This can be used to generate large strings for performance testing, for example, or just to create nice dotted lines when building a table of contents.

function rep(str, num, remain, result) {
 if (num < 2) {
 remain = (num == 1)
 } else {
 remain = (num % 2 == 1)
 result = rep(str, (num - remain) / 2)
 }
 return result result (remain ? str :"")
}

The function rep above is recursive, but performs very well under mawk, gawk and busybox awk. There are many other possible approaches (iterative, linear, very compacted, ones based on using printf() and gsub()), but tests showed them to be inferior in terms of performance, memory usage, code size, and sometimes all of the above.


Edit this page View other revisions Administration
Last edited 2009年03月01日 19:15 UTC by h-67-101-152-180.nycmny83.dynamic.covad.net (diff)

Powered by sdf Creative Commons License <pierre.gaston+awk@gmail.com>

Awk Wiki by #awk is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

AltStyle によって変換されたページ (->オリジナル) /