AWK example

AWK is the abbreviation of three developers’ names.

Function: analyze the file line by line based on pattern. 
Syntax:


awk '
BEGIN{}
/pattern/{}
END{}
'

In the BEGIN braces, we can declare the varables and seperators. 
The pattern part, replace with the pattern we need. In brances, specify the actions(print the line, add to counter and etc.) to take if the this line contains the text that satisfy such pattern. 
END{} part, print the patterns.

Example, suppose there is a file grades which contains the following records:

Abby F 80 87 83
Bob M 70 94 78
Cat F 89 85 88
Dog M 60 78 74

1. print the average grade for each student

awk '{print $1; print ($3+$4+$5)/3}' grades

The output is:

Abby
83.3333
Bob
80.6667
Cat
87.3333
Dog
70.6667

2. put the name and grades in one line sperated by different characters

awk '
BEGIN{ OFS=”->” }
{print $1,($3+$4+$5)/3}
' grades

output:
Abby 83.3333
Bob 80.6667
Cat 87.3333
Dog 70.6667

The output record fields are seperated by space, this is the default setting.

If we want to change it to other format, e.g. Cat->80.6667, this should be declare early with the key word OFS(output file seperator).


awk '
BEGIN{ OFS=”->” }
{print $1,($3+$4+$5)/3}
' grades

The output is:
Abby->83.3333
Bob->80.6667
Cat->87.3333
Dog->70.6667

3. Simple calculation: get the total grades based on gender.

In this situation, we need two variables male and female.
We first declare variable in BEGIN{}. 
Then in pattern match section, add different grades on each varialbe.

awk '
BEGIN{
fGrads=0;
mGrad=0
}
/M/{
mGrad = mGrad + $3 +$4+$5;
}
/F/{
fGrad = fGrad + $3 +$4+$5;
}
END{
print “Male”,mGrad;
print “Female”,fGrad;
}
' grades

In the above script, we have 2 patterns, M and F. Awk supports multiple patterns, but each pattern must be in a separate line.

4. The indexing

It start from 1 not zero. If the $0 is used, then it will print the whole line. 
 e.g.

awk '{print $0}' grades
Abby F 80 87 83
Bob M 70 94 78
Cat F 89 85 88
Dog M 60 78 74

The following command will only print the name.


awk '{print $1}' grades
Abby
Bob
Cat
Dog
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.