2 ways to iterate through an array in awk

Source: Internet
Author: User


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

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.