Search This Blog

Saturday, February 6, 2010

AWK with Examples

BASIC s ....

Lets take an example of a file abc.txt whose contents are 


$cat abc.txt

10 100 1000 one hundred
20 200 2000 two twohundred
30 300 3000 three threehundred


To print the first column


$awk '{print $1}' abc.txt
10
20
30

To print the first and second column

$awk '{print $1 $2}' abc.txt
10 100
20 200
30 300


By default space is the delimiter.You can change by flag -F like



$awk -OFS":" '{print $1 $4}' abc.txt

10:one
20:two
30:three

FLAGS:

NR                         Line Number
IFS                         Input File Seperator
OFS                       OutPut File Seperator

To count the no of  rows of a file(to replace wc -l abc.txt)

$awk 'BEGIN {count=0} {count=count+1} END {print count}' abc.txt
3

(OR)

simply

$ awk 'END {print NR}' abc.txt
3

To count the sum of  nth clolumns of a file(say 2 in this case)

$awk 'BEGIN {sum=0} {sum=sum+$2} END {print sum}' abc.txt
600

Lets go to some Advanced ...

Reading of input and printing can be managed by file seperators which is explained in a seperate post.

Loops, control statements, file handling and varible pasing can also be done in awk as explained below

<UNDER CONSTRUCTION> :)

No comments:

Post a Comment