Course


Practice AWK

AWK useful examples with hands-on playgrounds

AWK Examples

The best way to learn AWK is probably looking at some examples in a given context, let us create file `data.txt` file which has the following content:

Months Water Gas Elec Phone
Jan 647 2851 3310 1200
Feb 287 3544 25500 1000
Mar 238 3212 21900 1710
Apr 468 6986 35000 2000
May 124 1097 96300 13000

The csv formatted data file awk-data.csv has already been uploaded to the system, you should be good to go, just press the Run button!

AWK print function

By default Awk prints every line from the file.

Bash (5.0.0)
  • Input  

Action print with out any argument prints the whole line by default. So it prints all the lines of the file with out fail. Note that the actions need to be enclosed with in the braces.

AWK print with specific field:

Bash (5.0.0)
  • Input  

Print with the actions specified in the BEGIN section executed before AWK starts reading the lines from the input and END actions will be performed after completing the reading and processing the lines from the input.

Bash (5.0.0)
  • Input  

Complete example

Let's consider we want to find a total of al bills in all months in the data. We then create the following script:

Bash (5.0.0)
  • Input  

Note that it's a bash script that calls awk from inside and we have used FNR to detect the first row which we want to avoid in the sum calculation.

AWK built-in variables: As mentioned earlier, the built-in variable $NF represents number of field, in this case last field (5):

Bash (5.0.0)
  • Input  

AWK fields comparison >: Let's now find the months with water bills > 500:

Bash (5.0.0)
  • Input  

Self-contained AWK scripts example

In Linux systems self-contained AWK scripts can be constructed using. For example, a script that prints the content of a given file may be built by creating a file named printfile.awk with the following content:

#!/usr/bin/awk 
{ print $0 }
Bash (5.0.0)
  • Input  

Learn Practical Data Sciences with Bash Shell