Bash: 在输出中重用 printf 变量
Bash: Reuse printf variables in output
是否可以在格式化中多次使用传递给 printf
的变量?
例如,这一行:
printf 'Hi %s, welcome to %s. %s is a great place to work. Thanks %s.' "John" "The Icecream Factory"
如何“重用”printf
中的第一个和第二个变量?
我在想:
printf 'Hi %s[1], welcome to %s[2]. %s[1] is a great place to work. Thanks %s[2].' "John" "The Icecream Factory"
...但显然不是这样。
期望的输出
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 .
工作环境bash
Ubuntu 20.
虽然我认为使用 printf
的内置 bash
实现或独立的 GNU printf(1)
程序是不可能的,但如果您可以针对 zsh
相反,它的 printf
版本支持 POSIX-style printf(3)
参数索引:
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.
是否可以在格式化中多次使用传递给 printf
的变量?
例如,这一行:
printf 'Hi %s, welcome to %s. %s is a great place to work. Thanks %s.' "John" "The Icecream Factory"
如何“重用”printf
中的第一个和第二个变量?
我在想:
printf 'Hi %s[1], welcome to %s[2]. %s[1] is a great place to work. Thanks %s[2].' "John" "The Icecream Factory"
...但显然不是这样。
期望的输出
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 .
工作环境bash
Ubuntu 20.
虽然我认为使用 printf
的内置 bash
实现或独立的 GNU printf(1)
程序是不可能的,但如果您可以针对 zsh
相反,它的 printf
版本支持 POSIX-style printf(3)
参数索引:
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.