AWK Tutorial – Day 3

In this session, we will see few examples to understand the features discussed in the session 2.

# ExIf.awk
BEGIN {
     proto = 0
}
{
     if ( $1 !~ /^#/  && $ !~ /^$/ ) {
        proto++
     }
}
END {
    print “Total Number Protocols: ” proto
}

RUN: $ awk -f ExIf.awk /etc/protocols

# ExFor.awk
BEGIN {
     FS=”:”
     print “BEGIN”
}
{
    for (i=1; i <= 3; i++) {
           print $i
    }
}
END {
     print “Total lines in the input file is ” NR
}

RUN: $ awk -f ExFor.awk /etc/passwd

# ExWhile.awk

BEGIN {
     FS=”:”
     print “BEGIN”
}
{
    i = 1
    while (i <= 3) {
           print $i
           i++
    }
}
END {
     print “Total lines in the input file is ” NR
}

RUN: $ awk -f ExWhile.awk /etc/passwd

FUNCTIONS:

AWK comes with many built-in functions:

  • Numeric Functions: int(), sqrt(), exp(), log(), sin(), cos(), rand
  • String/Array Functions: sort(), index(), length(), match(), split(), substr(), tolower(), toupper()
  • System Functions: close(), system()
  • Time Functions: systime(), mktime(), strftime()

AWK support user-defined functions also. User can write own functions.

#ExFun.awk
function myadd ( a, b ) {
   return (a + b);
}
{
    sum = myadd($1, $2)
    print “Sum of ” $1 ” and ” $2 ” is ” sum
}

I will stop here. I hope, these sessions may helped you to get some basic idea about AWK. To know more about AWK, please read the man and info page of GAWK in your GNU/Linux computer (man awk or info gawk).

Advertisements
Tagged with:
Posted in Uncategorized
One comment on “AWK Tutorial – Day 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: