首页 > 解决方案 > 在 bash printf 格式中,如何在 muliples 占位符中使用相同的值

问题描述

我想将文件的行数放在 printf 字符串的两个占位符中

"%s lines: %s\n"
 ^          ^
 |here  and |here

所以我得到了两个wc -l::

$ do_stuff() { 
printf "%s ## lines: %5s\n" \
`cat $1 | wc -l` \
`cat $1 | wc -l`;
} 
$ do_stuff ./lpm/modelisator.py
426 ## lines:   426
$

有用!

有没有像 python 那样只给字符串一个值的方法?::

In [1]: '{0} line {0}'.format(426)                                                                                                                             
Out[1]: '426 line 426'

标签: bashprintf

解决方案


使用大括号扩展

printf '%s lines: %s\n' "$(wc -l <"$1")"{,}

推荐阅读