问题
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