为什么使用awk的数组输出顺序不正确? [英] Why the output of array using awk is not in right order?
问题描述
我有一个字符串:文件中的 Gatto piu bello anche cane
.我正在使用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
是带有该字符串的文件.
$INPUTFILE
is file with that string.
但是此代码的输出是:
anche
cane
Gatto
piu
bello
我不知道出了什么问题.
I have no idea what's the problem.
推荐答案
awk
实际上没有索引数组.它只有关联数组.这意味着您不能以保证的顺序遍历键.但是, split
确实保证填充的数组将使用数字1到 n
作为键.这意味着您可以在正确的数值范围内进行迭代,并使用这些数值对数组进行索引.
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];
}
这篇关于为什么使用awk的数组输出顺序不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!