AWK programming lesson 4

Unfortunately, I feel like this lesson is fairly weak compared to the others. It is little more than an incomplete list of functions, which the manpage does all by itself. But here it is.

The next component of AWK is all its special built-in functions.

AWK has functions that will make the average C programmer fairly happy. Things like sin()/cos()/tan(), rand(),index(), sprintf(), tolower(), system()

Functionally grouped, these can be viewed as follows:

Math tweaks

  +, -, /, *, sin(), cos(), tan(), atan(), sqrt(), rand(), srand()

All fairly self-explanitory, I hope.

String manipulation

index() will tell you if and where a string occurs in a substring.

match() is similar, but works for regular expressions.

sprintf() gives you a way to format output, and do conversions along the way. This should be familiar to anyone who has used printf() in C. For example,

   newstring=sprintf("one is a number %d, two is a string %s\n", one,  two);
   print  newstring

"%d" says "print the variable matching me, as a decimal number"
"%s" says "print the variable matching me, as a string"

So if you wanted to join two strings with no gaps, ONE way would be to use

    newstring=sprintf("%s%s", one,  two)

length() just gives you an easy way to count characters in a string, if you need that.

System level functions

system() lets you call potentially ANY executable on the system. The target executable can be either in your $PATH, or you can specify it by absolute path.

For example, the painful

    system("rm -rf $HOME");


    system("/bin/kill 1")

If you want to do more complex things, you'll probably end up doing something like

   sysstring=sprintf("somecommand %s %s", arg1,  arg2);

close() is an important function that is often overlooked. This is probably because there isn't an explicit open() call, so people don't expect to need a close() call. And for most purposes, you dont. But you DO NEED IT, if you are dealing with more than one output file.

Awk gives you the capability to open random files on the fly. For example

  /^file/	{ print $3 >> $2 }

should take the line "file output here-is-a-word", open the file 'output', and print 'here-is-a-word' to it.

AWK is "smart", in that it keeps track of what files you open, and KEEPS them open. It assumes if you opened a file once, you are likely to do it again. Unfortunately, this means if you open LOTS of files, you may run out of file descriptors. So, when you know you are done with a file, close it. So, to improve the above example, you might use something along the lines of:

  /^file/	{ if ( $2 !=  oldfile ) { close( oldfile) };
  			print $3 >> $2 ;  oldfile = $2; }

Top of AWK lessons - Next: Chapter 5 Prev: Chapter 3
bolthole main page