Use the field value as the array subscript, and the field array subscript
For the awk command, any expression can be used as the subscript of the array. Therefore, fields can also be used as subscript. The program in the following example is used to calculate the number of times that all names appear in the 2nd fields, and a new form of for loop is introduced.
For (index_value in array) statement
In the previous example, The for loop in the END block works as follows: the variable name is set to the index value of the count array. In each iteration of the for loop, to execute the print operation, the index value is printed first, and then the value stored in the element (the output order cannot be determined ).
Example
$ Cat datafile4
4234 Tom 43
4567 Arch 45
2008 running a 65
4571 Tom 22
3298 g0a 21
4622 Tom 53th
2345 Mary 24 $ awk '{count [$2] ++} END {for (name in count) print name, count [name]}'
Tom 3
Arch 1
Region A 2
Mary 1
Note: This awk statement uses the 2nd fields recorded as the subscript of the array count. The subscript of the array varies with the 2nd fields, so the first subscript of the array count is Tom. The value saved in count ["Tom"] is 1. Then, count ["Arch"], count ["distinct a"], and count ["Mary"] are successively set to 10. When Tom appears again in 2nd fields, the value of count ["Tom"] is added with 1, so its current value is 2. The re-emergence of Arch, category A, and Mary is similar.
Example
$ Awk '{dup [$2] ++; if (dup [$2]> 1) {name [$2] ++ }}\
END {print "The duplicates were "\
For (I in name) {print I, name [I]} 'datafile4
Tom 2
Region A 2
Note: The subscript of the array dup is the value of the 2nd fields, that is, the name of the person. The element values in the dup array are initially 0. Each time a record is processed, the value of the corresponding element is added with 1. If the name already exists, the value of the element that should be subject to the name changes to 2 and increases accordingly. If the value of an element in the dup array is greater than 1, a new array named name is created, and the value of 2nd fields is used as the subscript to record the name of a person who appears more than 1 times.
References: http://www.linuxawk.com/jiaocheng/274.html