AWK with Examples 9

Example 34: if - else statement.

awk '{ if ($0 ~ /h/)
       { print " H FOUND IN RECORD " NR}
    else
    { print " H NOT FOUND IN RECORD " NR}}' test1
   

 H NOT FOUND IN RECORD 1
 H FOUND IN RECORD 2
 H FOUND IN RECORD 3
 H FOUND IN RECORD 4
 H FOUND IN RECORD 5



Example 35: while statement

while (condtion)
body

awk '{ while ( i <=3 )
    {print i;
    i++}
  }' test1
 

1
2
3

>
do-while executes atleast once and then checks the condition.


Example 36: for loop
We can use for loop just as we use in C.

for (initialization,condition,increment)
body


awk ' { for(i=0;i<=3;i++){ print i}}' test1
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3
0
1
2
3


The loop executed for each record in the file.
The Limitation is that we can only do one initialization and increment in the for structure.

Like other langugage we cannot use "," to provide  multiple initializations or increments .


Example 37: For loop for arrays.
We also have another for structure for arrays.
Following is the syntax:

for ( i in arrayname)
 {
 do something with array[i]
 }
 

bos90631:sm017r awk '{ a[1]=1;a[2]=2;a[3]=3;
       for ( i in a)
           { print "Element no " i " is " a[i]
          }}' testx
Element no 2 is 2
Element no 3 is 3
Element no 1 is 1



Example 38: continue statement

This causes to skip the rest of the body of the loop causing the next cycle around the loop to begin.

 awk '{ a[1]=1;a[2]=2;a[3]=3;
       for ( i in a)
    { print "Element no: " i
      if (a[i]==2)
   { continue
   }
   print "Element value: " a[i]
    }}' testx
   

Element no: 2
Element no: 3
Element value: 3
Element no: 1
Element value: 1


Note that element is 2 it continues to the next cycle and ignores the rest of the code.

Example 39: next statement.
The next statement causes awk to immeditely stop the processing of current record and go on to the next record.
Rest of the code after next is not executed for the current record.
It starts entire processing for the next record.

NEXT is different from getline because of the fact that the next statement abandon the remaining code processing and starts from beginning for the new record.

But getline continues the remaining processing using newly fetchhed record.


awk ' {if ($1=="bhanu")
      next
   print $1}' test1
  

sukul
uma
shushant
himanshu


Note that when name was bhanu processing started with next record and thus
print statement was not executed for bhanu.


Example 40: exit statement
awk immediately exit the program and ignores remaining records.

awk ' {if ($1=="bhanu")
      exit
   print $1}' test1
  
sukul
uma


As soon as text "bhanu" is found the program exits.

No comments:

Post a Comment