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 2009 3100 6 index : 4 value :chevy beat 2005 33000 2 index : 5 value :honda...