Sort associative array with AWK

后端 未结 6 1478
逝去的感伤
逝去的感伤 2020-12-29 08:31

Here\'s my array (gawk script) :

myArray[\"peter\"] = 32
myArray[\"bob\"] = 5
myArray[\"john\"] = 463
myArray[\"jack\"] = 11

After sort, I

6条回答
  •  醉话见心
    2020-12-29 08:59

    Edit:

    Sort by values

    Oh! To sort the values, it's a bit of a kludge, but you can create a temporary array using a concatenation of the values and the indices of the original array as indices in the new array. Then you can asorti() the temporary array and split the concatenated values back into indices and values. If you can't follow that convoluted description, the code is much easier to understand. It's also very short.

    # right justify the integers into space-padded strings and cat the index
    # to create the new index
    for (i in myArray) tmpidx[sprintf("%12s", myArray[i]),i] = i
    num = asorti(tmpidx)
    j = 0
    for (i=1; i<=num; i++) {
        split(tmpidx[i], tmp, SUBSEP)
        indices[++j] = tmp[2]  # tmp[2] is the name
    }
    for (i=1; i<=num; i++) print indices[i], myArray[indices[i]]
    

    Edit 2:

    If you have GAWK 4, you can traverse the array by order of values without performing an explicit sort:

    #!/usr/bin/awk -f
    BEGIN {
        myArray["peter"] = 32
        myArray["bob"] = 5
        myArray["john"] = 463
        myArray["jack"] = 11
    
        PROCINFO["sorted_in"] = "@val_num_asc"
    
        for (i in myArray) {
            {print i, myArray[i]}}
        }
    
     }
    

    There are settings for traversing by index or value, ascending or descending and other options. You can also specify a custom function.

    Previous answer:

    Sort by indices

    If you have an AWK, such as gawk 3.1.2 or greater, which supports asorti():

    #!/usr/bin/awk -f
    BEGIN {
        myArray["peter"] = 32
        myArray["bob"] = 5
        myArray["john"] = 463
        myArray["jack"] = 11
    
        num = asorti(myArray, indices)
        for (i=1; i<=num; i++) print indices[i], myArray[indices[i]]
    }
    

    If you don't have asorti():

    #!/usr/bin/awk -f
    BEGIN {
        myArray["peter"] = 32
        myArray["bob"] = 5
        myArray["john"] = 463
        myArray["jack"] = 11
    
        for (i in myArray) indices[++j] = i
        num = asort(indices)
        for (i=1; i<=num; i++) print i, indices[i], myArray[indices[i]]
    }
    

提交回复
热议问题