Part1: Introduction to AWK


AWK is a tool to search for a given pattern and perform specific actions on it.

Syntax:
awk <options> ' <address> { <actions> }' <input|file(s)>


Examples:

awk '{print $0}'
hi this is a test
hi this is a test
^d

awk '{print $1, $4}'
hi this is a test
hi a
^d

awk '{print $1, $4}'
hi how
hi
are
are
you
you
^d

In the above examples, we did not mention the input explicitly. The input provided on the terminal is used for performing the print action. {print $0} prints the entire line and {print $1, $4} prints the 1st and 4th word in the input.

Let's see how input can be passed though a file.

echo hi how are you > awk.input
awk '{ print $0 } ' awk.input
hi how are you
awk '{ print "sapnwnewbie: ", $2, $3, $4 } ' awk.input
sapnwnewbie:  how are you

In all the above examples, we used the default seperator--space. Let's look at an example where we use colon (:) as seperator and define actions in a file.
The delimiter is specified with the option F and the action is specified with option f

echo 01:introduction to awk:simple examples > awk1.input
vi awk1.action
{ print "Post# ", $1, $2, $3}
:wq

awk -F":" -f awk1.action awk1.input
Post#  01 introduction to awk simple examples

More on AWK in the next post.

Comments

  1. Part2 posted here: http://sapnwnewbie.blogspot.com/2011/10/part2-regular-expressions-in-awk.html

    ReplyDelete

Post a Comment

Popular posts from this blog

OS/DB Migration - CMD. STR, TOC, EXT, R3load, DDLDBS.TPL and more

Fixing Inconsistent Table - Table activation fails due to inconsistency between DD and DB

301 Redirect Using SAP Web Dispatcher