Order problem of awk foreach
In PHP, the order the elements of array are always displayed as it created when traverse it with foreach, but in AWK it’s not the case, it seems in random order.
AWK version of foeach:
for (var in array) body
For example, when I run following awk script, the data display in random order, but not from 1 to 11.
awk '{i=1; while(i<=NF){arr[i]+=$i;i+=1}}END{for(i in arr){printf("%d=%d\n", i,arr[i]);}}' demo_data.txt
4=78913294 5=72533221 6=151446515 7=5690950 8=7163155 9=12854105 10=600865293 11=1071720068 1=193122485 2=113431670 3=306554155
Use following method instead in order to avoid confusing if the order is required:
for(i=1; i <= length(ARRAY); i++) body
demo_data.txt
9632108 5659241 15291349 3937536 3620112 7557648 283966 355788 639754 29978495 53467246 9657403 5669637 15327040 3946110 3625140 7571250 284820 358214 643034 30050377 53591701 9655299 5674226 15329525 3945152 3626141 7571293 284555 358477 643032 30048665 53592515 9658195 5671810 15330005 3950449 3629763 7580212 284571 357575 642146 30039707 53592070 9655504 5675401 15330905 3944973 3623397 7568370 285966 358200 644166 30049206 53592647 9658533 5674614 15333147 3941120 3630867 7571987 284417 358763 643180 30043939 53592253 9663355 5670377 15333732 3945271 3627271 7572542 284767 357710 642477 30043298 53592049 9661154 5674127 15335281 3946795 3626219 7573014 284636 358345 642981 30040659 53591935 9655119 5670961 15326080 3947739 3627210 7574949 285055 358086 643141 30048501 53592671 9654181 5668588 15322769 3947021 3627608 7574629 284603 358980 643583 30050409 53591390 9664004 5672546 15336550 3946492 3627060 7573552 285867 357617 643484 30038455 53592041 9653571 5670797 15324368 3945694 3628555 7574249 283991 357938 641929 30051367 53591913 9655395 5671722 15327117 3946222 3624930 7571152 283839 358734 642573 30051274 53592116 9655780 5672003 15327783 3942720 3625895 7568615 285084 357638 642722 30053798 53592918 9655786 5675341 15331127 3948867 3626483 7575350 284089 358135 642224 30044271 53592972 9655718 5672592 15328310 3946863 3629646 7576509 284260 359655 643915 30044217 53592951 9652834 5673940 15326774 3949866 3624831 7574697 284791 357703 642494 30048256 53592221 9656857 5670560 15327417 3947632 3629071 7576703 284152 358580 642732 30045527 53592379 9665378 5668883 15334261 3941470 3625433 7566903 283750 358483 642233 30048808 53592205 9656311 5674304 15330615 3945302 3627589 7572891 283771 358534 642305 30046064 53591875