Multi-dimensional awk array and multi-dimensional awk

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.