简体   繁体   English

Bash:在 output 中重用 printf 变量

[英]Bash: Reuse printf variables in output

Is it possible to use the variables passed to printf more than once in the formatting?是否可以在格式化中多次使用传递给printf的变量?

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 ?如何“重用” 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. ...但显然不是这样。

Desired output所需 output

Hi John, welcome to The Icecream Factory. The Icecream Factory is a great place to work. Thanks John.

Actual output实际 output

Hi John, welcome to The Icecream Factory.  is a great place to work. Thanks .

Working environment is bash in Ubuntu 20.工作环境为bash 20 中的 bash。

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: 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$ .通常,转换规范按顺序应用于每个参数,但它们可以通过将%替换为%n$*替换为*n$来明确指定要使用的第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.建议您不要将这种显式样式的引用与普通样式混合,并且此类混合 styles 的处理可能会在未来发生变化。

$ 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM