Wednesday 29 February 2012

Awk Command Examples

awk <pattern> '{print <stuff>}' <file>

The awk command something you will almost certainly come across when bash scripting, amongst other things, its very useful for preforming calculations on numbers which are in a file. for example:

say you have a file called 'scores.txt' with the following information

Karl 50 20 90 30
William 43 89 12 56
Natalie  93 87 46 10

Awk lets you preform calculations such as the following:

awk '{ print "Average for ", $1,"is", ($2+$3+$4+$5)/4}' score.txt

What's happening in the above command is awk is making use of the print function which basically does what it says. Each '$number' is a variable, for as shown above '$2' on the first line would equal 50, all these variables are being added together and then divided by the total number which gives us the average.

the output of this will be:
Average for Karl is 167.5
Average for William is 158
Average for Natalie is 228.5

I find this very useful for scripts, you can find out more with 'man awk'.

No comments:

Post a Comment