简体   繁体   中英

Sum of multiple columns in bash

I have an O/p file below and I'm looking for a bash and Perl solution:

Aggregate               total   used      avail   capacity
aggr0                   100     59       41      41%
aggr1                   200     100      100     50%
aggr2                   300     150     150      50%
aggr3                   400     200      200     50%

I would like to calculate the sum of all individual column except Col-1. The final state should look like this:

Aggregate               total   used      avail   capacity
aggr0                   100     59       41      41%
aggr1                   200     100      100     50%
aggr2                   300     150     150      50%
aggr3                   400     200      200     50%
=========================================================
                        1000   509       460   50.9%  (Used % of all aggr's)

infile是其中包含数据的文件

perl -ape 'next if $.==1; for my $i (1..4) { $s[$i] += $F[$i]; } END { $s[4]=sprintf("%.2f%%",$s[2]/$s[1]*100); $"="\t";print "total\t\t @s\n";}'

Perl is probably more suitable to this task, but it can be done from bash too :)

    tail -n +2 my_op_file.txt | while read n c1 c2 c3 c4;do
        total=$(($total + $c1 ))
        used=$(($used + $c2 ))
        avail=$(($avail + $c3 ))
        capacity=$(($capacity + ${c4%%%}))
        echo $total $used $avail $capacity
    done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM