Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables in printf format

Tags:

printf

awk

Suppose I have a file like this:

$ cat a
hello this is a sentence
and this is another one

And I want to print the first two columns with some padding in between them. As this padding may change, I can for example use 7:

$ awk '{printf "%7-s%s\n", $1, $2}' a
hello  this
and    this

Or 17:

$ awk '{printf "%17-s%s\n", $1, $2}' a
hello            this
and              this

Or 25, or... you see the point: the number may vary.

Then a question popped: is it possible to assign a variable to this N, instead of hardcoding the integer in the %N-s format?

I tried these things without success:

$ awk '{n=7; printf "%{n}-s%s\n", $1, $2}' a
%{n}-shello
%{n}-sand

$ awk '{n=7; printf "%n-s%s\n", $1, $2}' a
%n-shello
%n-sand

Ideally I would like to know if it is possible to do this. If it is not, what would be the best workaround?

like image 868
fedorqui 'SO stop harming' Avatar asked Aug 20 '14 14:08

fedorqui 'SO stop harming'


People also ask

Can you use a variable in printf?

Using printf function, we can print the value of a variable. In order to print the variable value, we must instruct the printf function the following details, 1. specify the format of variable.

What is the use of %% in C for printf?

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

What is %d %f %s in C?

It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc. The format specifier in printf() and scanf() are mostly the same but there is some difference which we will see.

Can we use %d in printf?

In this program, we have used the printf() function to print the integer num and the C-string my_name . printf("num = %d \n", num); printf("My name is %s", my_name); Here, %d is replaced by the num variable in the output.


2 Answers

If you use * in your format string, it gets a number from the arguments

awk '{printf "%*-s%s\n", 17, $1, $2}' file
hello            this
and              this

awk '{printf "%*-s%s\n", 7, $1, $2}' file
hello  this
and    this

As read in The GNU Awk User’s Guide #5.5.3 Modifiers for printf Formats:

The C library printf’s dynamic width and prec capability (for example, "%*.*s") is supported. Instead of supplying explicit width and/or prec values in the format string, they are passed in the argument list. For example:

w = 5
p = 3
s = "abcdefg"
printf "%*.*s\n", w, p, s

is exactly equivalent to:

s = "abcdefg"
printf "%5.3s\n", s
like image 129
jaypal singh Avatar answered Oct 21 '22 05:10

jaypal singh


does this count?

idea is building the "dynamic" fmt, used for printf.

kent$   awk '{n=7;fmt="%"n"-s%s\n"; printf fmt, $1, $2}' f 
hello  this
and    this
like image 24
Kent Avatar answered Oct 21 '22 03:10

Kent