繁体   English   中英

BASH:使用键对关联数组进行排序

[英]BASH: sorting an associative array with their keys

所以我在 shell 脚本中对 arrays 很费劲,尤其是处理键值排序。 这就是我所拥有的

declare -A array
Array[0]=(0)
Array[1]=(4)
Array[2]=(6)
Array[3]=(1)

所以在每个数组中我们有 (0,4,6,1),如果我们将它们从大到小排序,它将是 (6,4,1,0)。 现在,我想知道我是否可以对值的键进行排序,然后将它们放入一个像这样的新数组中(有点像对它们进行排名):

newArray[0]=(2) # 2 which was the key for 6
newArray[1]=(1) # 1 which was the key for 4
newArray[2]=(3) # 3 which was the key for 1
newArray[3]=(0) # 0 which was the key for 0

我尝试了一些解决方案,但它们的编码太硬,在某些情况下不起作用。 任何帮助将不胜感激。

  1. 创建一个索引+值的元组。
  2. 对价值进行排序。
  3. 删除值。
  4. 读入数组。

array=(0 4 6 1)

tmp=$(
   # for every index in the array
   for ((i = 0; i < ${#array[@]}; ++i)); do
       # output the index, space, an array value on every line
       echo "$i ${array[i]}"
   done |
   # sort lines using Key as second column Numeric Reverse
   sort -k2nr |
   # using space as Delimiter, extract first Field from each line
   cut -d' ' -f1
)
# Load tmp into an array separated by newlines.
readarray -t newArray <<<"$tmp"
# output
declare -p newArray

输出:

declare -a newArray=([0]="2" [1]="1" [2]="3" [3]="0")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM