10

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.

7
  • @JonathanLeffler ok, thank you. Then how could i solve this problem? Commented Dec 19, 2015 at 20:38
  • The sequence in which the keys in an array are listed by (key in array) is undefined. Sometimes it will appear to be sorted; it is not guaranteed. The POSIX specification for awk says: for (variable in array) which shall iterate, assigning each index of array to variable in an unspecified order. Commented Dec 19, 2015 at 20:40
  • If you're using Bash, chances are you have GNU Awk. Look up the sort functions. Commented Dec 19, 2015 at 20:42
  • @JonathanLeffler, thank you, now i understand. What will be the best way to print array in right order? Commented Dec 19, 2015 at 20:43
  • What is the 'right order'? Sorted order or order of appearance in the line? If order in line is relevant, determine the number of elements in the array (returned by split) and iterate over them. If it is alphabetic order, as I assumed at first, then look to the sorting functions, or write your own. Commented Dec 19, 2015 at 20:49

2 Answers 2

17

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

That is assuming, of course, that one follows the convention of numbering the array starting with 1. That's not a technical requirement, and documentation is in conflict as to whether arrays should be numbered from 0 or from 1. (Of course, if all we're using is split() to populate the array, then my argument is moot...)
@chepner Thank you! This is what i was looking for.
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.