Introducing UNIX and Linux |
AwkOverview |
Formatted outputYou will recall the use of
will print on your screen Hello chris!
In Awk there is also a command called { printf "The first field is %s\n", $1 } Worked exampleWrite an Awk script which, when given input in two columns representing a person's first name followed by their family name, such as Abraham Lincoln John Kennedy Benjamin Disraeli will reverse the order of the names, and separate them with a comma: Lincoln, Abraham Kennedy, John Disraeli, Benjamin Solution: Using { printf "%s, %s\n", $2, $1 } Alternatively, using { print $2 ", " $1 } Before we can experiment much further with Awk, we need some data. Consider the problem of a grocery bill - you have purchased some vegetables that are priced per kilogram, and you buy a number of kilograms of various different vegetables. Create a file containing in column 1 the names of vegetables, in column 2 the price per kilogram, and in column 3 the number of kilograms purchased, something like: potatoes 0.50 5 carrots 0.80 2.5 peas 2.20 1 beans 2.10 2 artichokes 8.50 0.5 sweetcorn 0.90 3 Name this file Recall that when using { printf "%s %.2f %.1f\n", $1, $2, $3 } Try this, using
Note what happens when you have a whole number as one of the last two columns - it is printed with the relevant number of decimal places containing zeros: potatoes 0.50 5.0 carrots 0.80 2.5 peas 2.20 1.0 beans 2.10 2.0 artichokes 8.50 0.5 sweetcorn 0.90 3.0 Simple arithmetic can be performed by Awk, with the same operators and conventions as
Try it - but remember that this will be done for each line of
input, so if you pipe the contents of a file to this command, the
output will have the same number of lines as the input, each line
being the number Worked exampleWrite an Awk script to reformat the data in
I bought 5.0 kilos of potatoes at 50p per kilo I bought 2.5 kilos of carrots at 80p per kilo ... Solution: Use { printf "I bought %.1f kilos of %s at %dp per kilo\n", $3, $1, 100*$2 } If you wish to do floating-point arithmetic in Awk, and your
script contains some whole numbers, then Awk will automatically
convert those integers to floating-point numbers when it is
sensible to do so. Thus Worked exampleWrite an Awk script which uses the data in
potatoes cost 2.50 carrots cost 2.00 ... Solution: We can calculate the total cost for each vegetable by multiplying the second and third fields together. { printf "%s cost %.2f\n", $1, $2*$3 } Earlier on, we used Worked exampleDisplay the current year.
For comparison, the other two methods would be written:
It is up to you to decide which one you think is clearest. |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck