LINUX AWK Tutorial Series | Chapter 9

Hello, In this chapter I will continue the concepts of arrays in AWK.

Now I am going share, how are we going to use the arrays with the file. I will use the same file Employee data. I will mostly be using awk scripts in the examples.

Let's start with an example


Example 1: 

We want to calculate the food amount for each employee. That will be calculated based on the salary of the employee. That will be 1% of the total salary.

    
[himanshu@oel7 AWK]$ cat array_food
BEGIN{FS=","}
{
food[$1]=$4*.01
}
END{
for(i in food)
print i "==" food[i]
}

Confused about what for will do here. For loop will execute for each index in the array.




So here the array index would the name of the employees (food[$1]) and calculating the food amount based on the salary which is the 4th field.



Example 2: 

Now I want to delete the array for Robert in output.

Syntax

delete array_name[index]  ==> This will delete one array element
delete array_name[index]  ==> Delete entire array


[himanshu@oel7 AWK]$ cat array_food
BEGIN{FS=","}
{
food[$1]=$4*.01
}
END{
delete food["Robert"]
for(i in food)
print i "==" food[i]
}






Try at Home: With the below awk script please try to execute and see what output we get.

[himanshu@oel7 AWK]$ cat array_food
BEGIN{FS=","}
{
food[$1]=$4*.01
}
END{
delete food
for(i in food)
print i "==" food[i]
}




Example 3:

In earlier chapters, we have discussed built-in variables related to arrays, Lets see them in our scripts.

ARGC: Number of command-line arguments.  
ARGV: Array which stores command line arguments.

[himanshu@oel7 AWK]$ cat builtin_arry_var
BEGIN{
print ("Arguments total" ARGC);
for (i=0;i<=ARGC-1;i++)
print ARGV[i]
}


Here I am using both ARGC and ARGV. The first index at i=0 will take the awk as the first argument. so the total argument here would be 2.






Example 4:

One more built-in variable is ENVIRON. It is also an array of environmental variables.
The array index would be the environment variables name.





Here I am printing value for the environment variable USER using the normal method and using AWK also doing the same.


Hope these would be clear.



More chapters will continue.



If you like please follow and comment