Based on other recent questions you posted, you appear to be struggling with the basics of the awk
language.
I will not attempt to answer your original question, but instead try to get you on the way in your investigation of the awk language.
It is true that the syntax of awk expressions is similar to c. However there are some important differences.
I would recommend that you spend some time reading a primer on awk and find some exercises. Try for instance the Gnu Awk Getting Started.
That said, there are two major differences with C
that I will highlight here:
- Types
Awk only uses strings and numbers -- it decides based on context whether it needs to treat input as text or as a number. In some cases
you may need to force conversion to string or to a number.
- Structure
An Awk program always follows the same structure of a series of patterns, each followed by an action, enclosed in curly braces: pattern {
action }
:
pattern { action }
pattern { action }
.
.
.
pattern { action }
Patterns can be regular expressions or comparisons of strings or numbers.
If a pattern evaluates as true, the associated action is executed.
An empty pattern always triggers an action. The {
action }
part is optional and is equivalent to { print }
.
An empty pattern with no action will do nothing.
Some patterns like BEGIN
and END
get special treatment. Before reading stdin or opening any files, awk will first collect all BEGIN
statements in the program and execute their associated actions in order.
It will then start processing stdin or any files given and subject each line to all other pattern/action pairs in order.
Once all input is exhausted, all files are closed, and awk will process the actions belonging to all END
patterns, again in order of appearance.
You can use BEGIN
action to initialize variables. END
actions are typically used to report summaries.
A warning: Quite often we see people trying to pass data from the shell by partially unquoting the awk script, or by using double quotes. Don't do this; instead, use the awk -v
option to pass on parameters into the program:
a="two"
b="strings"
awk -v a=$a \
-v b=$b \
'BEGIN {
print a, b
}'
two strings