RubyGuides
Share this post!

Variables with Awk

Awk comes with some predefined variables, like NF for number of fields or OFS for field separator. If you wanna know more about these ‘man awk’ and search for ‘Built-in Variables’. In this post we are going to talk about using your own variables just like in any other programming language. If you are new to awk start here: http://www.blackbytes.info/2012/01/intro-to-awk/

Awk variables example

If we want to find the biggest number in a file we could do something like this:

There is a few interesting things in this line. To start with we don’t need to declare our variable which is cool, but what I want you to pay attention to is that variables in awk don’t have a leading $, neither when assigning or accessing the value, this may be a bit confusing if you are used to do bash scripting. Here the leading $ always references fields so if you used $max instead it wouldn’t work as expected.

Then there is this END statement, which allows us to execute some code after all the lines of input have been processed. There is also a BEGIN statement which does exactly what you would expect.

Finally here is an Awk reference card you may find useful: http://www.catonmat.net/download/awk.cheat.sheet.pdf