As an expert AWK programmer, all we need to know in it are its internals.
AWK follows a simple workflow − Read, Execute, and Repeat.
The below diagram will depict the workflow of AWK −
AWK reads a line from the input stream (file, pipe, or stdin) and stores the data in memory.
All AWK commands will be applied sequentially on the input data. By default , AWK executes commands on each and every line. We can limit its flow by providing patterns.
This process will be repeatsed until the file reaches its end.
Let us now understand the program structure of AWK.
The syntax of the BEGIN block is as follows −
First, the BEGIN block gets executed at program start-up. It executes only once.
BEGIN Block is a good place to initialize variables. BEGIN is an AWK keyword and hence it must always be in upper-case.
Please make a note that this block is optional.
The syntax of the body block is as below−
The body block applies AWK commands on every input line. By default, AWK executes commands on every line. We can limit this by providing patterns.Please note that, there are no keywords for this Body block.
The syntax of the END block is as follows −
The END block will execute at the end of the program. Here, END is an AWK keyword and hence it must always be in upper-case.
Note that this block is optional.
For suppose, let us create a file marks.txt which contains the serial number, name of the student, subject name, and number of marks obtained.
When this code is executed, it produces the below result −
At the beginning, AWK will print the header from the BEGIN block. Then in the next section i.e body block, it reads a line from a file and executes AWK's print command which will print the contents on the standard output stream. This process will get repeated until file reaches the end.
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.