Book Image

Learning AWK Programming

By : Kalkhanda
5 (1)
Book Image

Learning AWK Programming

5 (1)
By: Kalkhanda

Overview of this book

AWK is one of the most primitive and powerful utilities which exists in all Unix and Unix-like distributions. It is used as a command-line utility when performing a basic text-processing operation, and as programming language when dealing with complex text-processing and mining tasks. With this book, you will have the required expertise to practice advanced AWK programming in real-life examples. The book starts off with an introduction to AWK essentials. You will then be introduced to regular expressions, AWK variables and constants, arrays and AWK functions and more. The book then delves deeper into more complex tasks, such as printing formatted output in AWK, control flow statements, GNU's implementation of AWK covering the advanced features of GNU AWK, such as network communication, debugging, and inter-process communication in the GAWK programming language which is not easily possible with AWK. By the end of this book, the reader will have worked on the practical implementation of text processing and pattern matching using AWK to perform routine tasks.
Table of Contents (11 chapters)

Assignment in arrays

Array elements can be assigned values like any other AWK variables, as follows:

arr[index] = value

In the following example, we take the cars database file cars.dat. Here, we make the record number the index to the array and store each record as a value to the corresponding array element. The system variable NR is used as the index for the array as it gets incremented for each record. In the end, we print the array elements using a for loop as follows:

$ vi basic_array.awk

{
arr[NR] = $0
}
END{
for ( x=1; x<= NR; x++)
print "index : "x, "value :"arr[x]
}

$ awk -f basic_array.awk cars.dat

The output of the execution of the preceding code is as follows:

index : 1 value :maruti          swift       2007        50000       5
index : 2 value :honda city 2005 60000 3
index : 3 value :maruti dezire...