在 Bash 中创建尾随空格的字符串
我想循环关联数组并以一种很好的方式打印出键/值对。因此,我想以这样的方式缩进这些值,使它们都从各自键后面的相同位置开始。
这是一个例子:
declare -A my_array
my_array["k 1"]="value one"
my_array["key two"]="value two"
for key in "${!my_array[@]}"; do
echo "$key: ${my_array[$key]}"
done
输出是
k 1: value one
key two: value two
我想要的输出是(对于任意密钥长度):
k 1: value one
key two: value two
I'd like to loop over an associative array and print out the key / value pairs in a nice way. Therefore I'd like to indent the values in such a way, that they all start at the same position behind their respective keys.
Here's an example:
declare -A my_array
my_array["k 1"]="value one"
my_array["key two"]="value two"
for key in "${!my_array[@]}"; do
echo "$key: ${my_array[$key]}"
done
The output is
k 1: value one
key two: value two
The output I'd like to have would be (for arbitrary key length):
k 1: value one
key two: value two
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
printf
,如果您的系统有的话:将最大密钥长度硬编码为 20,但您当然可以添加代码来迭代密钥、计算最大值,然后使用它来构建
printf
格式化字符串。You can use
printf
, if your system has it:This hard-codes the maximum key length to 20, but you can of course add code that iterates over the keys, computes the maximum, and then uses that to build the
printf
formatting string.使用
printf
而不是echo
。您将获得格式化的所有功能,例如 30 个字符的字段的%30s
。Use
printf
instead ofecho
. You'll get all the power of formatting, e.g.%30s
for a field of 30 characters.