O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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       5index : 2 value :honda city ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required