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

前端 未结 2 1390
轮回少年
轮回少年 2021-01-21 05:28

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:

相关标签:
2条回答
  • 2021-01-21 05:57

    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.

    0 讨论(0)
  • 2021-01-21 06:11

    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];
    }
    
    0 讨论(0)
提交回复
热议问题