Skip to main content
3 of 6
added 74 characters in body
Giles
  • 907
  • 7
  • 20

looping in awk, calculating percentages for each integer within its column

I have a line of code I want to use, but I want it to loop through all the columns in a file, I can do it outside of awk but its really slow. My problem is that I'm not good at looping inside awk, I can run a simple awk loop but this needs something that I can't do yet. So if you can explain how you solve this question it will help me in the future.

The awk command at the moment will output the percentage equivalent of each integer within the selected column ($i). This is the current awk command: awk -F ',' -v x=$i 'FNR==NR{s+=$x;next;} {printf "%s\n",100*$x/s}' File File

Example input for the above command:

1    
4    
3    
2    

Example output for the above command:

10.00000    
40.00000    
30.00000        
20.00000        

I need to loop in awk for all of the columns in the file (the file column number is unknown)

so if the input had more than one column, the example input could be:

1,4,2    
4,4,1  
3,1,6    
2,1,1    

Example output:

10.00000,40.00000,20.00000    
40.00000,40.00000,10.00000  
30.00000,10.00000,60.00000    
20.00000,10.00000,10.00000    
Giles
  • 907
  • 7
  • 20