Florian Feldhaus
Florian Feldhaus

Reputation: 5932

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

Upvotes: 1

Views: 6519

Answers (2)

mouviciel
mouviciel

Reputation: 67831

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

Upvotes: 1

unwind
unwind

Reputation: 399733

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.

Upvotes: 4

Related Questions