Tutorial Two

Formatting Fields into Columns

A common use of awk is to process input files by formatting them, and then output the results in the chosen form.

For example, suppose we have a file containing statistics on different countries populations, specifying

It may well be stored in the following format :-

Canada:3852:25:North America
USA:3615:237:North America
Brazil:3286:134:South America
England:94:56:Europe
France:211:55:Europe
Japan:144:120:Asia
Mexico:762:78:North America
China:3705:1032:Asia
India:1267:746:Asia

If we stored the above data into a file called "countries" we could use awk to format it with the following command :

If you would like to see what the above does press the following button for a

The -F: option instructed awk to separate the input data into fields delimited by colons. As there is no pattern specified on the above awk processes each line of input, passing it to the printf command which is used to produce the output in the format we require.

If you would like a closer look at what the above printf command does press the button to see how it works.

Alternatively, if you want to try out an exercise relating to formatting fields into columns why not try out the programming exercise for tutorial two?

[Help] [Provide some feedback] [Go to Previous Page]