Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use printf to print a character multiple times?

Tags:

printf

awk

gawk

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}'
-
like image 844
fedorqui 'SO stop harming' Avatar asked May 18 '16 09:05

fedorqui 'SO stop harming'


People also ask

What does %% do in printf?

% indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.

How do I print a character in printf?

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.

Can you multiply characters in C?

Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language.

How do I print a character multiple times in C++?

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.


2 Answers

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

like image 181
Maurice1408 Avatar answered Oct 19 '22 06:10

Maurice1408


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.

like image 28
user98761 Avatar answered Oct 19 '22 04:10

user98761