HomePage RecentChanges Frequently Asked Questions Japanese Espańol

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.