In awk, arrays are random, and elements in the same array are not necessarily of the same type, and the following table can be numbers or characters.
There are two ways to iterate through an array:
1. Methods similar to C + +
#-----------------------------/chapter11/ex11-30.sh------------------#! /bin/awk-fbegin { #定义数组 stu[1]= "200200110" stu[2]= "200200164" stu[3]= " 200200167" stu[4]= " 200200168 " stu[5]=" 200200172 " #计算数组的长度 len=length (stu) #通过循环遍历数组 for (i=1;i<=len;i++) { print i,stu[i] }}
Attention:
This method requires the length of the array to be computed first, which can be used with the length () function, mentioned earlier can also be used to calculate the length of the string, which can also be used to calculate the length of the array, the argument in length brackets is the name of the array, and returns the length of the array.
Also, the subscript of an array is calculated starting from 1 , which differs from C + +, java.
2. Using the in command
#-----------------------------/chapter11/ex11-31.sh------------------#! /bin/awk-fbegin { #定义数组 arr[1]= "Tim" arr[2]= "John" arr["a"]=12 arr[3]=3.1415 arr[4]=5 arr[99]=23 #遍历数组 for (n in arr) { print arr[n] }}
Parse: The in command is used in a For loop statement, and all elements of the array can be traversed. However, the order of the outputs is no longer in the order defined by the array. If you want to iterate through an array in order, you must use the first way to iterate over the array.
However, when the subscript is not unified as a number when defining an array, we cannot traverse it using the above method, only using the in command.
2 ways to iterate through an array in awk