Using printf
, one can print a character multiple times:
$ printf "%0.s-" {1..5}
-----
In awk
I know that I can do something like:
$ awk 'BEGIN {while (i++ < 5) printf "-"}'
-----
But I wonder if awk's printf
allows this as well.
I went through the printf
modifiers page but could not find how. All in all, what the printf from Bash does is to expand {1..5}
and print a -
for every parameter it gets, so it is equivalent to saying
$ printf "%0.s-" hello how are you 42
-----
However, I lack the knowledge on how to mimic this behaviour with awk's printf, if it is possible, because this fails:
$ awk 'BEGIN {printf "%0.s-", 1 2 3 4 5}'
-
% indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.
Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'. Neither single % will print anything nor it will show any error or warning.
Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language.
In C++, there is a way to initialize a string with a value. It can be used to print a character as many times as we want. While declaring a string, it can be initialized by using the feature provided by c++. It takes 2 arguments.
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
If you can assume a (modest) upper bound on how long the result should be, how about something like this:
l = 5;
print substr("---------------------", 1, l);
Besides being dead simple, this has the benefit that it works in versions of AWK that lack the "gensub()" function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With