Arrays are an important data structure in AWK that allow you to store and manipulate collections of values or elements. In AWK, there are two types of arrays: indexed arrays and associative arrays.
– **Indexed Arrays:** Indexed arrays are arrays where elements are accessed using an index or position number. The index starts at 1 and increments by 1 for each subsequent element. The syntax for declaring and accessing an indexed array is as follows:
` array_name[index] = value;
Here is an example of an indexed array:
` # Declare an indexed array fruit[1] = "apple"; fruit[2] = "banana"; fruit[3] = "cherry"; # Access an element of the array print fruit[2]; # Output: banana
– **Associative Arrays:** Associative arrays are arrays where elements are accessed using a key or string instead of an index number. The key can be any string value, and elements can be added, removed, or modified dynamically. The syntax for declaring and accessing an associative array is as follows:
` array_name[key] = value;
Here is an example of an associative array:
` # Declare an associative array price["apple"] = 0.50; price["banana"] = 0.25; price["cherry"] = 1.00; # Access anelement of the array print price["banana"]; # Output: 0.25
Arrays can be used to store and manipulate data in AWK programs. Here are some examples of how arrays can be used in AWK:
– Using an indexed array to store and process command line arguments:
` # Store command line arguments in an indexed array for (i = 1; i <= ARGC; i++) { args[i] = ARGV[i]; } # Print the arguments in reverse order for (i = ARGC; i >= 1; i--) { print args[i]; }
In this example, we use an indexed array `args` to store the command line arguments passed to the AWK program. We then use a for loop to iterate over the elements of the array in reverse order and print them.
– Using an associative array to count the frequency of words in a text file:
` # Count the frequency of words in a text file while (getline < "file.txt") { for (i = 1; i <= NF; i++) { count[$i]++; } } # Print the word count for (word in count) { print word, count[word]; }
In this example, we use an associative array `count` to count the frequency of words in a text file.We read each line of the file using a while loop, split the line into words using the predefined field separator `FS`, and increment the count of each word in the `count` array. We then use another for loop to iterate over the elements of the array and print the word and its count.
Arrays provide a powerful and flexible way to store and process data in AWK programs. You can use indexed arrays to store sequences of values or elements, and associative arrays to store and manipulate data using keys or strings. You can also use arrays in conjunction with control structures, user-defined functions, and built-in functions to implement complex algorithms and operations.