Is it possible to use the variables passed to printf
more than once in the formatting?
For example, with this line:
printf 'Hi %s, welcome to %s. %s is a great place to work. Thanks %s.' "John" "The Icecream Factory"
How can I "reuse" the first and second variables in printf
?
I'm thinking something like:
printf 'Hi %s[1], welcome to %s[2]. %s[1] is a great place to work. Thanks %s[2].' "John" "The Icecream Factory"
... but obviously that's not it.
Hi John, welcome to The Icecream Factory. The Icecream Factory is a great place to work. Thanks John.
Hi John, welcome to The Icecream Factory. is a great place to work. Thanks .
Working environment is bash
in Ubuntu 20.
While I don't think it's possible using either the built-in bash
implementation of printf
or the freestanding GNU printf(1)
program, if you can target zsh
instead, its version of printf
supports POSIX-style printf(3)
argument indexing:
Normally, conversion specifications are applied to each argument in order but they can explicitly specify the
n
th argument is to be used by replacing%
by%n$
and*
by*n$
. It is recommended that you do not mix references of this explicit style with the normal style and the handling of such mixed styles may be subject to future change.
$ printf 'Hi %1$s, welcome to %2$s. %2$s is a great place to work. Thanks %1$s.\n' "John" "The Icecream Factory"
Hi John, welcome to The Icecream Factory. The Icecream Factory is a great place to work. Thanks John.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.