Renaud Pacalet
Renaud Pacalet

Reputation: 29345

How to perform pattern substitution on the keys of a bash associative array

I need to perform a pattern substitution on the keys of a bash associative array. Example:

$ declare -A aa=( [A]=0 [B]=1 [C]=2 )

To prefix the values with foo_ one can use:

$ echo --${aa[@]/#/foo_}--
--foo_0 foo_1 foo_2--

But how to prefix the keys? This does not work (at least in GNU bash, version 4.3.30(1)-release):

$ echo --${!aa[@]/#/foo_}-- # <- does not work
----

Is there a better way than the following workaround?

$ declare -a keys=( ${!aa[@]} )
$ echo --${keys[@]/#/foo_}--
--foo_A foo_B foo_C--

Upvotes: 2

Views: 137

Answers (1)

anubhava
anubhava

Reputation: 786091

You can use printf:

printf 'foo_%s\n' "${!aa[@]}"

foo_A
foo_B
foo_C

Upvotes: 2

Related Questions