在Bash中将索引数组转换为关联数组 [英] Convert an indexed array into an associative array in Bash
问题描述
目前,我正在努力寻找以下任一问题的解决方案:
At present, I’m struggling to find solution to either of the following problems:
- 如何将普通数组(索引从0开始的索引数组)转换为关联数组,其中value成为键,而value本身就是值.
- 从索引数组创建一个新的assoc数组,其中值是键.而这在一个声明中.我知道可以很好地使用循环来完成此操作,但是对于包含近500,000个元素的大型数组而言,循环是一项开销.
-
根据mysql sql查询的结果创建一个assoc数组.我通常从mysql sql查询结果创建索引数组,如下所示:
- 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.
- 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.
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")
"
其中$ DB_NAME是指向数据库名称字符串的变量.
where $DB_NAME is the variable pointing to DB name string.
推荐答案
这是使用sed
的一种方法.请注意,这仅在原始数组的所有元素都不包含空格的情况下起作用.
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') )"
sed
命令采用每个数组元素"x",并将其替换为字符串"[x] = x",适用于关联数组分配.
The sed
command takes each array element 'x' and replaces it with the string '[x]=x', suitable for an associative array assignment.
这篇关于在Bash中将索引数组转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!