简体   繁体   English

在Bash中使用尾随空格创建字符串

[英]Create string with trailing spaces in Bash

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

You can use printf , if your system has it: 您可以使用printf ,如果您的系统具有它:

printf "%20s: %s" "$key" "${my_array[$key]}"

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. 这会将最大密钥长度硬编码为20,但是您当然可以添加在密钥上进行迭代,计算最大长度然后使用该代码构建printf格式化字符串的代码。

Use printf instead of echo . 使用printf代替echo You'll get all the power of formatting, eg %30s for a field of 30 characters. 您将获得格式化的全部功能,例如,对于30个字符的字段, %30s

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

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