Create string with trailing spaces in Bash

僤鯓⒐⒋嵵緔 提交于 2021-02-10 19:50:41

问题


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

回答1:


You can use printf, if your system has it:

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.




回答2:


Use printf instead of echo. You'll get all the power of formatting, e.g. %30s for a field of 30 characters.



来源:https://stackoverflow.com/questions/8833608/create-string-with-trailing-spaces-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!