Tuesday, 27 March 2018

AWK Programming Tutorial - Hello world with awk

Hello world with awk: This is the second article from the tutorial series on awk and in this article, we will be learning to some different ways to print Hello world with awk. In fact, there in no need to have a separate article for this, but usually we do start with a Hello world program while learning any programming language. Never mind, we start.


In the first article in this tutorial series on awk, Introduction to awk, we learned the basic syntax to use awk on command line and it is as below:

$ awk '<instructions>' <input_file/s>

Alternately, we can have these instructions stored in a script file, then the syntax becomes:

$ awk -f <script_file> <input_file/s>

So, in order to print Hello world, we need a print statement in the instruction and a file. Lets create a file myFile with any random contents.

$ cat myFile
This is some random content, awk will ignore it

Now, we write our awk command with the print "Hello world" as instruction and myFile as the input file.

$ awk ' {print "Hello world"} ' myFile
Hello world

In above example, awk will execute the print statement for every single line from the input file. As our input file has only one line, awk reads it and prints Hello world.





Another way, we can have the string Hello world written in myFile and use print $0 statement in the instruction. $0 will print entire line read from input file.

$ cat myFile
Hello world

$ awk ' {print $0} ' myFile
Hello world

From above two examples, it is pretty much clear that, we need an input file to feed awk command, or it will read input from stdin. You can check this by simply not mentioning the input file name in awk from first example and hitting ENTER key a few times.

$ awk ' {print "Hello world"} '
[ENTER]
Hello world
[ENTER]
Hello world
[ENTER]
Hello world
[Ctrl + C]

Yet another way, we can use BEGIN block in our instruction. BEGIN block is executed before any input lines are read. Similarly, we have END block which gets executed once all of the lines from input file are read. Both BEGIN and END blocks are optional.

$ awk ' BEGIN { print "Hello world" } '
Hello world

We will cover both BEGIN and END blocks in a separate article. Well, that's all for the scope of this one and put your feedback and suggestions in the comments section below.

0 comments:

Post a Comment