Thursday, June 19, 2014

awk: Program Elements(2)

1. numeric expressions
./script_1:
 #! /bin/bash  
   
 echo "Hello world" |  
 awk '{  
     s="123";  
     n=s + 0; # "+0" can convert a string to number  
     n++;   #Increment Operator  
     print n; #output 124  
   
     #if input string is not a complete number, awk will  
     #try its best to convert "from the beginning"  
     s="123kkk";   
     n=s + 0;  
     print n; #output 123  
   
     s="kkk123";  
     n=s + 0; # "+0" convert string to number   
     print n; #output 0  
   
     n=2;  
     n^=3; # n = n*n*n      
     print n; # output 8  
   
     print "================"  
     true && n=3; #short circuit, "n=3" is only executed when "true"  
     print n; #output 8  
     false && n=0; #"n=0" is not executed in this case  
     print n; #output 8  
   
     n1=10;  
     n2=20;  
     n=(n1<n2)?n1:n2;  
     print n; #output 10  
   
     n=n1=n2=100;   
     #assignment operator is right associative  
     #firstly assign 100 to n2, then assign 100 to n1  
     #lastly assign 100 to n  
     #equal to : n=(n1=(n2=100));  
     print n,n1,n2; #output 100 100 100  
    }'  
   

2. Scalar Variables
./text:
 Hello world!!  
 Amazing world!  


./script_1:
 #! /bin/bash  
   
 cat text | awk '{  
   #n1, n2 are scalar variables, they are created automatically  
   #when assigning value to them  
   n1=$1;  
   n2=$2;  
   
   #awk variables are case sensitive, N1 is different from variable  
   #n1.   
   N1=$0;  
   print "n1:",n1;  
   print "N1:",N1;  
   
   #output:  
   #n1: Hello  
   #N1: Hello world!!  
   #n1: Amazing  
   #N1: Amazing world!  
 }'  

No comments:

Post a Comment