AWK數組

AWK關聯數組最好的事情之一就是 - 索引不必是連續的設定的數; 我們可以使用字符串或數字作爲數組的索引。也沒有需要事先聲明數組的大小- 數組可以在運行時擴展/收縮。本教程介紹AWK數組的例子。

array_name[index]=value

創建

[jerry]\$ awk 'BEGIN {
fruits["mango"]="yellow";
fruits["orange"]="orange"
print fruits["orange"] "\n" fruits["mango"]
}'

orange
yellow

刪除

delete array_name[index]

[jerry]\$ awk 'BEGIN {
fruits["mango"]="yellow";
fruits["orange"]="orange";
delete fruits["orange"];
print fruits["orange"]
}'

多維數組

AWK只支持一維數組。但是我們可以很容易地模擬使用一維陣列本身的多維陣列。

100 200 300 400 500 600 700 800 900

array["0,0"] = 100

[jerry]\$ awk 'BEGIN {
array["0,0"] = 100;
array["0,1"] = 200;
array["0,2"] = 300;
array["1,0"] = 400;
array["1,1"] = 500;
array["1,2"] = 600;

print array elements

print "array[0,0] = " array["0,0"];
print "array[0,1] = " array["0,1"];
print "array[0,2] = " array["0,2"];
print "array[1,0] = " array["1,0"];
print "array[1,1] = " array["1,1"];
print "array[1,2] = " array["1,2"];
}'

array[0,0] = 100
array[0,1] = 200
array[0,2] = 300
array[1,0] = 400
array[1,1] = 500
array[1,2] = 600