Pages

Thursday, August 22, 2019

AWK Associative array

Example HTML page

arrayname[string]=value

Syntax:

for (var in arrayname)
actions


Code to identify shell used by how many users

Sample Code

BEGIN {
        FS=":"
}
{user_shells[$7] +=1}
END{
        for (shell in user_shells)
                print shell "\t\t" user_shells[shell]
}




How it Works

We are creating an array name called user_shells for which we are mentioning index item is  present on field 7. If the value of field 7 repeats then the respective index value is increased by 1. 

to access the array we will be using for loop. for loop of awk will work slight differently compare to bash for loop. 

In case of awk for loop, variable mentioned will be used as a index of the array. So printing the declared variable in awk will print the array index and the second part will print the array values for the respective index.