Go to the first, previous, next, last section, table of contents.


Examples of print Statements

Here is an example of printing a string that contains embedded newlines (the `\n' is an escape sequence, used to represent the newline character; see section Escape Sequences):

$ awk 'BEGIN { print "line one\nline two\nline three" }'
-| line one
-| line two
-| line three

Here is an example that prints the first two fields of each input record, with a space between them:

$ awk '{ print $1, $2 }' inventory-shipped
-| Jan 13
-| Feb 15
-| Mar 15
...

A common mistake in using the print statement is to omit the comma between two items. This often has the effect of making the items run together in the output, with no space. The reason for this is that juxtaposing two string expressions in awk means to concatenate them. Here is the same program, without the comma:

$ awk '{ print $1 $2 }' inventory-shipped
-| Jan13
-| Feb15
-| Mar15
...

To someone unfamiliar with the file `inventory-shipped', neither example's output makes much sense. A heading line at the beginning would make it clearer. Let's add some headings to our table of months ($1) and green crates shipped ($2). We do this using the BEGIN pattern (see section The BEGIN and END Special Patterns) to force the headings to be printed only once:

awk 'BEGIN {  print "Month Crates"
              print "----- ------" }
           {  print $1, $2 }' inventory-shipped

Did you already guess what happens? When run, the program prints the following:

Month Crates
----- ------
Jan 13
Feb 15
Mar 15
...

The headings and the table data don't line up! We can fix this by printing some spaces between the two fields:

awk 'BEGIN { print "Month Crates"
             print "----- ------" }
           { print $1, "     ", $2 }' inventory-shipped

You can imagine that this way of lining up columns can get pretty complicated when you have many columns to fix. Counting spaces for two or three columns can be simple, but more than this and you can get lost quite easily. This is why the printf statement was created (see section Using printf Statements for Fancier Printing); one of its specialties is lining up columns of data.

As a side point, you can continue either a print or printf statement simply by putting a newline after any comma (see section awk Statements Versus Lines).


Go to the first, previous, next, last section, table of contents.