Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

awk

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.

like image 473
codeNinja7 Avatar asked Dec 10 '22 19:12

codeNinja7


1 Answers

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];
}
like image 168
chepner Avatar answered Jan 17 '23 19:01

chepner