Sunday, June 22, 2014

awk: Output Redirection

1. Truncate vs Append
text:
 Hello world!  
 Hello Amazing world!  

text2:
 Hello Chicago  
 Hello Los Angeles  
 Hello Boston  
 Hello Atlantic  

script_1:
 #! /bin/bash  
   
 # print ">" will truncate the file only at "opening"  
 # time, which is the first time when print command   
 # is touching "text". For following executions of  
 # actions, it will add output to end of existing   
 # contents.  
 awk '{  
   print $0 > "text";  
 }' text2;  
   
 cat text;  
 #output:  
 #Hello Chicago  
 #Hello Los Angeles  
 #Hello Boston  
 #Hello Atlantic  
   
 # For each execution of action, print command will  
 # open the "text", which also truncate the file, since  
 # we close the file every time after writing content  
 # inside. So in the end, "text" only contains last  
 # record.  
 awk '{  
   print $0 > "text";  
   close("text");  
 }' text2;  
   
 cat text;  
 #Output:  
 #Hello Atlantic  
   
 #print ">>" will append content to the end of "text"  
 #file. When opening the file, it won't truncate the  
 #existing file.  
 awk '{  
   print $0 >> "text";  
 }' text2;  
   
 cat text;  
 #output:  
 #Hello Atlantic  
 #Hello Chicago  
 #Hello Los Angeles  
 #Hello Boston  
 #Hello Atlantic  

2.Pipeline to external command
text2:
 3 Chicago  
 5 Los Angeles  
 1 Boston  
 4 Atlantic  

script_1:
 #! /bin/bash  
   
 awk 'BEGIN {  
   command = "sort -k1 > text";  
 }  
 {  print $0 | command; }  
 END { close(command); }' text2  
   
 #After using pipeline to feed input into "command",  
 #close(command) will free resources on awk side, also,  
 #it will run the command, and process all input content   
 #fed before, lastly feed output into text file  
   
 cat text;  
 #output:  
 #1 Boston  
 #3 Chicago  
 #4 Atlantic  
 #5 Los Angeles  
   
 awk 'BEGIN {  
   command = "sort -k1 >text";  
 }  
 { print $0 | command;   
  close(command);}' text2  
   
 #since we are doing the "close" every time we give  
 #input to command, then command is executed every time  
 #with only one line record. During the execution, it  
 # will truncate "text" file. So in the end, text file  
 #only contains last line of text2.  
   
 cat text;    
 #output:  
 #4 Atlantic  
   
 awk 'BEGIN {  
   command = "sort -k1 >>text";  
 }  
 { print $0 | command;   
  close(command);}' text2  
 #Every time when we use close command to clear out  
 #the input buffer, and execute the command with the  
 #content in buffer(only one line of record), the  
 #record is just appended to the end of text file  
 #So in the end, 4 four records in text2 are appended  
 #into text file with the original order.  
   
 cat text;  
 #output:  
 #4 Atlantic  
 #3 Chicago  
 #5 Los Angeles  
 #1 Boston  
 #4 Atlantic  

No comments:

Post a Comment