Multi-dimensional awk array and multi-dimensional awk
Although the awk command does not claim to support multi-dimensional arrays, it provides a method to define multi-dimensional arrays. Awk defines multi-dimensional arrays by concatenating multiple subscripts into strings. subscripts are separated by the value of the built-in variable SUBSEP. The value of the variable SUBSEP is "\ 034", which is a non-printable character and rarely used. Therefore, it is unlikely to be used as a character in the subscript. The expression matrix [0348] is actually an array matrix [2 SUBSEP 8]. The converted result is matrix ["2 \"]. Therefore, the subscript is a unique identifier in the associated array.
Example
$ Cat datafile
1 2 3 4 5
2 3 4 5 6
7 8 9 0 1
$ Awk '{
Nf = NF
For (x = 1; x <NF; x ++ ){
Matrix [NR, x] = $ x
}
} END {
For (x = 1; x <NR; x ++ ){
For (y = 1; y <nf; y ++ ){
Printf "% d", matrix [x, y]
}
Printf "\ n"
}
} 'Datafile
(Output)
1 2 3 4 5
2 3 4 5 6
7 8 9 0 1
Note:
1. Assign the NF value (number of fields) to the variable nf (this program assumes that each record is composed of five fields ).
2. Go to the for loop and save the field numbers of each field in the input line to variable x.
3. matrix is a two-dimensional array. The value of each field is assigned to the array element whose subscript is NR (Record Number of the current record) and x.
4. The two for loops in the END block are used to traverse the matrix array and print the saved values in the array. This example is only used to illustrate how to use multi-dimensional arrays.
References: http://www.linuxawk.com/jiaocheng/290.html