在 Bash 中创建带有尾随空格的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8833608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create string with trailing spaces in Bash
提问by Florian Feldhaus
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
回答by unwind
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 printfformatting string.
这将最大密钥长度硬编码为 20,但您当然可以添加迭代密钥、计算最大值,然后使用它来构建printf格式化字符串的代码。
回答by mouviciel
Use printfinstead of echo. You'll get all the power of formatting, e.g. %30sfor a field of 30 characters.
使用printf代替echo。您将获得格式化的所有功能,例如,%30s对于 30 个字符的字段。

