How to Add Column with Percentage

前端 未结 4 1650
半阙折子戏
半阙折子戏 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:39

    Perhaps there is better way but I would pass file twice.

    Content of 'infile':

    1       10 
    2       10
    3       20
    4       40
    

    Content of 'script.awk':

    BEGIN {
            ## Tab as field separator.
            FS = "\t";
    }
    
    ## First pass of input file. Get total from second field.
    ARGIND == 1 {
            total += $2;
            next;
    }
    
    ## Second pass of input file. Print each original line and percentage as third field.
    {
            printf( "%s\t%2.2f\n", $0, $2 * 100 / total );
    }
    

    Run the script in my linux box:

    gawk -f script.awk infile infile
    

    And result:

    1       10      12.50
    2       10      12.50
    3       20      25.00
    4       40      50.00
    

提交回复
热议问题