Revision 3 not available (showing current revision instead)

CookBook


Just started, the aim of this page is to collect small pieces of code that illustrate specific problems.

Looping on all the fields(columns) of a Record(lines)

Fields are numbered from 1 to NF, so you can easily use a for loop, and the derefence operator, for instance to print each field matching foo:

for (i=1;i<=NF;i++) 
{
  if ($i ~ /foo/)
  {
    print $i
  }
}

Edit this answer


How to test if an array is empty

You can test if an array is empty using this function:

 function empty(a,   i) { for(i in a) return 0; return 1} 

This function comes from comp.lang.awk see this post

Edit this answer


How to "join" an array

Edit this answer


How to find the last matching substring on a line for a given regular expression

The function 'match' sets RSTART to the index of each match and RLENGTH to its length, and returns 0 when no matches exist. To find the last match on a line, then, all that is necessary is to call it and remove the match until it no longer finds matches, and take the final match.

function lastmatch(re, line,        result) {
    while(match(line, re)) {
        result = substr(line, RSTART, RLENGTH)
        line = substr(line, RSTART+RLENGTH)
    }
    return result
}

Edit this answer