Saturday, June 28, 2014

awk: string functions(3)

1. String Reconstruction
There is no utility to reconstruct the string from the array, but we can write one by ourselves.
script_1:
 #! /bin/bash  
   
 awk 'BEGIN {  
   arr[1]="Hello";  
   arr[2]="world!";  
   
   print reconstruct(arr, 2, " ");  
   #Output:  
   #Hello world!  
 }  
   
 function reconstruct(arr, len, fs,  i, s)  
 {  
   if(len >= 1)  
   {  
     s=arr[1];  
     for(i=2;i<=len;i++)  
       s=s fs arr[i];  
   }  
   
   return s;  
 }'  

2. String Formatting
script_1:
 #! /bin/bash  
   
 awk 'BEGIN {  
   printf("%10d\n", 100);  
   printf("%10s\n", "Hello");  
 #output:  
 #    100  
 #   Hello  
   
   s1=sprintf("%10d", 100);  
   s2=sprintf("%10s", "Hello");  
   print s1;  
   print s2;  
 #output:  
 #    100  
 #   Hello  
 }'  

No comments:

Post a Comment