facebook twitter youtube
by Amit Gupta - one comment

We already had discussed about what is AWK, an introduction. Now you need to understand basic structure of AWK command;

An AWK command can be broken in three parts.


BEGIN { print "START" }
      { print         }
END   { print "STOP"  }

BEGIN, END blocks are optional and run only once. While, in the other hand, the middle block is run for every line of given file. This is the bock where actual processing logic is written.

For example

awk ‘/article-stack\.com/’ post-contents.txt

In above command, BEGIN & END blocks are missing. Above command will search for ‘/article-stack\.com/’ in every line.

Another Example; Try all below examples

awk ‘BEGIN{print FILENAME}’ filename
awk ‘{print FILENAME}’ filename
awk ‘END{print FILENAME}’ filename

/*FILENAME is a reserved keyword. It prints the name of input file, we will understand it later in element section.*/

Here I am considering that input file for above example is having more than 1 line. Second AWK command will print filename N times where N stands for number of lines in input file. Because it runs for every line. While the first and 3rd line shall run only once. So they’ll print FILENAME one time only.

You can use BEGIN block to set initial parameters, while you can use END block to print result as summary.

Some more examples for better understanding:

1. To print number of lines in a file [one time only]

awk 'END{print NR}' filename

2. To Print no. of entries of a month

Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Leave a Reply