如何在bash中以printf格式获取特定参数?

时间:2016-11-07 12:29:42

标签: bash printf parameter-passing

需要构建字符串foobar is not foo and not bar

我期待类似的代码:

$ printf "%1%2 is not %1 and not %2" 'foo' 'bar'

那么,如何传递一个特定的论点?

我的环境:

$ bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)

1 个答案:

答案 0 :(得分:-3)

语法与C printf函数相同。

$ printf '%1$s%2$s is not %1$s and not %2$s' 'foo' 'bar'

实际上,如果您只需要连接一些字符串,则不需要printf。您可以在字符串中使用命名变量:

a=foo
b=bar
echo "$a$b is not $a and not $b"