3

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.

2
  • awk's array is associative array, take a look, if it can help you. Commented Feb 11, 2014 at 10:52
  • You are probably better off using a language other than shell to do this type of data processing. Commented Feb 11, 2014 at 13:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.