Awk基本入门[5] Awk Associative Arrays
1、Assigning Array Elements
In Awk, arrays are associative, i.e. an array contains multiple index/value pairs. The index doesn't need to be a continuous set of numbers; in fact it can be a string or a number, and you don't need to specify the size of the array.
Syntax:
arrayname[string]=value
- arrayname is the name of the array.
- string is the index of an array.
- value is any value assigning to the element of the array.
The following is a simple array assignment example:
$ cat array-assign.awk BEGIN { item[101]="HD Camcorder"; item[102]="Refrigerator"; item[103]="MP3 Player"; item[104]="Tennis Racket"; item[105]="Laser Printer"; item[1001]="Tennis Ball"; item[55]="Laptop"; item["na"]="Not Available"; print item["101"]; print item[102]; print item["103"]; print item[104]; print item["105"]; print item[1001]; print item[55]; print item["na"]; }
$ awk -f array-assign.awk HD Camcorder Refrigerator MP3 Player Tennis Racket Laser Printer Tennis Ball Laptop Not Available
Please note the following in the above example:
• Array indexes are not in sequence. It didn't even have to start from 0 or 1. It really started from 101 .. 105, then jumped to 1001, then came down to 55, then it had a string index "na".
• Array indexes can be string. The last item in this array has an index string. i.e. "na" is the index.
• You don't need to initialize or even define the array in awk; you don't need to specify the total array size before you have to use it.
• The naming convention of an awk array is same as the naming convention of an awk variable.
From awk's point of view, the index of the array is always a string.Even when you pass a number for the index, awk will treat it as string index. Both of the following are the same.
item[101]="HD Camcorder" item["101"]="HD Camcorder"