Sort associative array with AWK

后端 未结 6 1466
逝去的感伤
逝去的感伤 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:48

    Use the Unix sort command with the pipe, keeps Awk code simple and follow Unix philosophy
    Create a input file with values seperated by comma
    peter,32
    jack,11
    john,463
    bob,5

    Create a sort.awk file with the code

    BEGIN { FS=","; }
    {
        myArray[$1]=$2;
    }
    END {
        for (name in myArray)
            printf ("%s,%d\n", name, myArray[name]) | "sort -t, -k2 -n"
    }
    

    Run the program, should give you the output
    $ awk -f sort.awk data
    bob,5
    jack,11
    peter,32
    john,463

提交回复
热议问题