TransWikia.com

How to add 2 column values and find out percentage value?

Unix & Linux Asked by user3559780 on November 9, 2021

When I do df, I get folowing results:

Filesystem     1K-blocks     Used Available Use% Mounted on
udev             1529860        4   1529856   1% /dev
tmpfs             308116      960    307156   1% /run
/dev/sda1       47929224 40768468   4703004  90% /
none                   4        0         4   0% /sys/fs/cgroup
none                5120        0      5120   0% /run/lock
none             1540572       76   1540496   1% /run/shm
none              102400       44    102356   1% /run/user
Shared         168479740 78002196  90477544  47% /media/sf_Shared
/dev/sr0           83904    83904         0 100% /media/amitk/VBox_GAs_6.0.41
 

Now, I want to add the value of "1K-blocks" and "Used" for sda1 and Shared, in order to calculate the ratio of the sums, and store them in a file EmmcSpace.txt.

  • In the above example, ths sums for "1K-blocks" would be 47929224 + 168479740 =216408964, and for "Used" 40768468 + 78002196 = 118770664.

  • I then want to do (118770664 *100)/ 216408964=54.88 and store the result in the file.

But I am stucked with this calculation part.I don’t want "use%" column for some reason. So how do I move ahead so that finally in the EmmcSpace.txt file there should only percentage value i.e. 54.88 or 54 and nothing else

#include<stdio.h>
    #include<unistd.h>
    #include<string.h>
    int main(void)
    {   
        system("df |grep sda1 |awk -F ' ' '{print $2, $3}' >EmmcSpace.txt");
        system("df |grep Shared |awk -F ' ' '{print $2, $3}' >>EmmcSpace.txt");
        
        system("awk '{total1 = total1 + $1}END{print total1}' EmmcSpace.txt >>EmmcSpace.txt");
        system("awk '{total2 = total2 + $2}END{print total2}' EmmcSpace.txt >>EmmcSpace.txt");
        
        //system("awk '{printf  (($total2 *100) / ($total1))}' EmmcSpace.txt");
        //system("total='expr $total1 * 100' '{print total}'");
        //system("total=`expr $total1 * 100` ");
        //system("total=`expr $total / total2`");
        
        return 0;
    }
    

One Answer

You can actually use awk for the entire task:

df | awk '$1~/^Shared/ || $1~/^/dev/sda1/ {total+=$2;used+=$3} END{printf("%.2fn",100*used/total)}' > EmmcSpace.txt

will add the "1k blocks" and "used" column for all lines that start with /dev/sda1 and Shared in variables total and used, respectively, and print the ratio of the sums at the end.

The output is then redirected into the file EmmcSpace.txt.

Answered by AdminBee on November 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP