AWK Workflow - AWK

What is AWK Workflow?

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 Workflow

Read

AWK reads a line from the input stream (file, pipe, or stdin) and stores the data in memory.

Execute

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.

Repeat

This process will be repeatsed until the file reaches its end.

Program Structure

Let us now understand the program structure of AWK.

BEGIN block

The syntax of the BEGIN block is as follows −

Syntax

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.


Body Block

The syntax of the body block is as below−

Syntax

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.

END Block

The syntax of the END block is as follows −

Syntax

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 −

Output

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 DMCA.com Protection Status

AWK Topics