Why the output of array using awk is not in right order?

偶尔善良 提交于 2021-01-20 07:28:45

问题


I have a string: Gatto piu bello anche cane in file. I am using awk to split it and to put it into array. But the output is not in the right order. My code is:

while (getline < "'"$INPUTFILE"'") {
        text = $0;
}
split (text,text_arr," ");
for (i in text_arr) {
    print text_arr[i];
}

$INPUTFILE is file with that string.

But the output of this code is:

anche
cane
Gatto
piu
bello

I have no idea what's the problem.


回答1:


awk doesn't actually have indexed arrays; it only has associative arrays. This means you can't iterate over the keys in an guaranteed order. split, however, does promise that the array it populates will use the numbers 1 through n as the keys. This means you can iterate over the correct numerical range, and use those to index the array.

for (i=1; i<=length(text_arr); i++) {
    print text_arr[i];
}



回答2:


Although there is an accepted answer that's not the idiomatic. awk already parses the record to fields and the fields can be accessed with $1 to $NF. You can then iterate over the fields to do whatever you want.

{ for(i=1;i<=NF;i++) 
     do_something_with $i
}

Perhaps you have a more complex requirement but not clear from the description.



来源:https://stackoverflow.com/questions/34375020/why-the-output-of-array-using-awk-is-not-in-right-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!