Hello, World

It has become a convention to introduce a programming language by demonstrating the “Hello, world” program. Showing how this program works in awk will demonstrate just how unconventional awk is. In fact, it’s necessary to show several different approaches to printing “Hello, world.”

In the first example, we create a file named test that contains a single line. This example shows a script that contains the print statement:

$ echo 'this line of data is ignored' > test
$ awk '{ print "Hello, world" }' test
Hello, world

This script has only a single action, which is enclosed in braces. That action is to execute the print statement for each line of input. In this case, the test file contains only a single line; thus, the action occurs once. Note that the input line is read but never output.

Now let’s look at another example. Here, we use a file that contains the line “Hello, world.”

$ cat test2
Hello, world
$ awk '{ print }' test2
Hello, world

In this example, “Hello, world” appears in the input file. The same result is achieved because the print statement, without arguments, simply outputs each line of input. If there were additional lines of input, they would be output as well.

Both of these examples illustrate that awk is usually input-driven. That is, nothing happens unless there are lines of input on which to act. When you invoke the awk program, it reads the script that you supply, checking the syntax of your instructions. Then awk attempts to execute the instructions for ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.