Convert an indexed array into an associative array

2019-05-25 02:20发布

问题:

At present, I’m struggling to find solution to either of the following problems:

  1. how to convert a normal array (indexed array with index starting at 0) into an associative array where value becomes a key and value itself is the value.
  2. Create a new assoc array from indexed array where values are keys. And this in a single statement. I know it can very well be done using a loop but for a huge sized array containing almost 500,000 elements, a loop is an overhead.
  3. Create an assoc array from the result of mysql sql query. I normally create an indexed array from a mysql sql query result as below:

    mapfile -t a_dummy <<< "$(mysql -u root –disable-column-names –silent -B -e "select * from dummy_tbl;" "$DB_NAME")"

where $DB_NAME is the variable pointing to DB name string.

回答1:

Here's one way, using sed. Note that this will only work, however, if none of the elements of the original array contain whitespace.

declare -A "newArray=( $(echo ${oldArray[@]} | sed 's/[^ ]*/[&]=&/g') )"

The sed command takes each array element 'x' and replaces it with the string '[x]=x', suitable for an associative array assignment.