"awk" Command

Learn all about awk command

HOME

one of the most prominent text-processing utility on GNU/Linux. It can solve complex text processing tasks with a few lines of code.AWK is an interpreted programming language. It is very powerful and specially designed for text processing. Its name is derived from the family names of its authors - Alfred Aho, Peter Weinberger, and Brian Kernighan.

To become an expert AWK programmer, you need to know its internals. AWK follows a simple workflow - Read, Execute, and Repeat.

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

Execute
All AWK commands are applied sequentially on the input. By default AWK execute commands on every line. We can restrict this by providing patterns.

Repeat
This process repeats until the file reaches its end.


The basic syntax of AWK:

awk 'BEGIN {BEGIN_BLOCK_ACTION} {BODY_BLOCK_FOR_EACHLINE} END {END_BLOCK_ACTION}' filename
                
(1) BEGIN block Syntax
BEGIN {awk-commands}
                
The BEGIN block gets executed once at program start-up. It's good place to initialize variables or print some meaningful statements. 'BEGIN' is an awk keyword so it must be in upper-case; kindly note that this block is optional.

(2) Body Block Syntax
/pattern/ {awk-commands}
                
AWK command applies the body block on every input line. By Default it executes commands on every line; but it can be restricted by providing patterns. Note that there are no keywords for the Body block.

(3) END Block Syntax
END {awk-commands}
                
The END block executes once at the end of the program. END is an AWK keyword so it must be in upper-case. Kindly, note that this block is optional.

More Information on awk can be found through its manual page or help:
root:~# awk --help

root:~# man awk
                
Let us create cricketer_details.txt file which has the following content, which will be used in examples.
root:~#cat cricketer_details.txt
10  Virat      OneDown     Right   5200
20  Rohit      Opener      Right   5540
30  Dhawan     Opener      Left    7340
40  Yuvaraj    Middle      Left    9300
50  Rahane     OneDown     Right   6200