Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an indexed array into an associative array in Bash

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.

like image 809
sameer oak Avatar asked Mar 17 '26 22:03

sameer oak


1 Answers

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.

like image 135
chepner Avatar answered Mar 19 '26 12:03

chepner