简体   繁体   English

为什么使用awk的数组输出不正确?

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

I have a string: Gatto piu bello anche cane in file. 我有一个字符串: Gatto piu bello anche cane in file。 I am using awk to split it and to put it into array. 我使用awk分割它并将其放入数组。 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. $INPUTFILE是包含该字符串的文件。

But the output of this code is: 但是这段代码的输出是:

anche
cane
Gatto
piu
bello

I have no idea what's the problem. 我不知道是什么问题。

awk doesn't actually have indexed arrays; awk实际上没有索引数组; 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. 但是, split确实承诺它填充的数组将使用数字1到n作为键。 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];
}

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 . awk已经将记录解析为字段,并且可以使用$1$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. 也许你有一个更复杂的要求,但从描述中不清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM