Monday, February 17, 2014

AWK by examples

General

 $ awk -F":" '{ print "username: " $1 "\t\tobserved:" $3 }' sam.txt   
 $ awk -F":" '$3==0.222' sam.txt  


In awk, curly braces are used to group blocks of code together.  `-F ":"` indicates the field separator of `sam.txt`. `\t ` is tab separator. `$1` and `$3` are field (column) 1 and 3.

The BEGIN and END blocks

BEGIN { Actions}
{ACTION} # Action for everyline in a file
END { Actions } 

There are many programming situations where you may need to execute initialization code before awk begins processing the text from the input file. For such situations, awk allows you to define a BEGIN block. We used a BEGIN block in the previous example. Because the BEGIN block is evaluated before awk starts processing the input file, it's an excellent place to initialize the FS (field separator) variable, print a heading, or initialize other global variables that you'll reference later in the program.

 awk -F":" 'BEGIN {print "Username\tDHAZ";}  
 {print $1, "\t", $3;}  
 END{print "Report List\n------------------";  
 }' sam.txt  



No comments:

Post a Comment