How to Add Column with Percentage

前端 未结 4 1647
半阙折子戏
半阙折子戏 2021-02-08 09:53

I would like to calculate percentage of value in each line out of all lines and add it as another column. Input (delimiter is \\t):

1   10      
2   10
3   20
4          


        
4条回答
  •  深忆病人
    2021-02-08 10:27

    You can do it in a couple of passes

    #!/bin/bash
    
    total=$(awk '{total=total+$2}END{print total}' file)
    awk -v total=$total '{ printf ("%s\t%s\t%.2f\n", $1, $2, ($2/total)*100)}' file
    

提交回复
热议问题