Sunday, June 15, 2014

awk: Program Elements(1)

1. awk comments

awkCommand:
 #Comment 1  
 /Chicago/ #Comment 2  
 /Chicago/ { #Note: "{" has to start from here instead of next line  
   #If "{" starts from here, the action will be not for   
   #above pattern only  
   print $1,"Middle West!"   
 }  
 /Middle West!/ { print $1, "America!" }  
 BEGIN { print "Begin awk 1!" }  
 END { print "End awk!" }  
 BEGIN { print "Begin awk 2!" }  

awkInput:
 Hello world!  
 Hello New York!  
 Hello Chicago!  


script_1:
 #! /bin/bash  
   
 awk -f awkCommand <awkInput  
   
 awk '{ \  
      #Comment 5 \  
      print $0 #Comment 6\  
    }' <awkInput  
 #Good to go
   
 awk '{ print $0; #Comment 7 }' <awkInput  
 #error, comment can't co-exist with with code at the same  
 #line if we are trying to present all code in the same  
 #line  
   

2. string expressions
 #! /bin/bash  
   
 echo "Hello world!" | \  
 awk '{   
      s=$0; #allocate memory for string  
      s = "Hello New York!";  
      #allocate memory for new string and memory  
      #space for old string is already reclaimed  
   
      print s;   
      #Note: $s is not good, using awk variable is just  
      #variable itself  
      #Output:  
      #Hello New York!  
   
      len=length(s);   
      #length is a string function to get the string length  
      print len;  
      #output: 15       
   
      s1="abc"  
      s2="b"  
   
      print (s1==s2)?"Equal":"Unequal";   
      #Output: Unequal  
      print (s1>s2)?"greater":"not greater";  
      #Output: not greater  
   
      s=s1 s2 #concatenating 2 strings together  
      print s  
      #Output: abcb  
   
      s=s s s  
      print s  
      #output: abcbabcbabcb  
   
      num=123  
      s=123 ""  
      print s #output 123, convert number to string here
      print length(s) #output 3  
   
      print ("ABC" ~ "^[A-Z]*$")? "match!":"not match!"  
      print ("ABC" !~ "^[A-Z].$")? "Not match!":"match!"  
      #operator "~" and "!~" are used to test regular expressions  
      #matching. ~ means match, !~ means not match!  
   
      print "\"" #output "  
      print "\\\\" #output \\  
      #special characters need to be protected in double quote string  
    }'  
   

No comments:

Post a Comment