Search code examples
bashshellarithmetic-expressions

Defining a new variable from division of another two variables with bash script


I have 2 variables which are up_votes and down_votes from a csv dataset. I am trying to create a new variable as percentage of up_votes / total_votes. For example, up_votes=296 down_votes=255, my output should be 53.7 but I get 25600. Here is my equations.

    x=$col3
    y=$col3+$col4
    z=($x/$y)*100
    ans=$z

Solution

  • You need to use external programs to do calculations because bash does not support float point arithmetic

    #!/bin/bash
    
    
    votes="topic1,0,0 topic2,296,255 topic3,3,4"
    
    for vote_data in $votes ; do
        topic=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\1/'`
        up_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\2/'`
        down_votes=`echo $vote_data|sed -r 's/([^,]*),([^,]*),(.*)/\3/'`
    
    #    echo "$topic , up: $up_votes, down: $down_votes"
    
        total=`awk "BEGIN {print ($up_votes+$down_votes)}"`
        if [ $total -eq 0 ];then
        ans=divbyzero
        else
        ans=`awk "BEGIN {print 100.0*$up_votes/( $up_votes+$down_votes)}"`
        fi
        echo "$topic $ans [ $up_votes / $down_votes ]"
    
    done
    

    output:

    topic1 divbyzero [ 0 / 0 ]
    topic2 53.7205 [ 296 / 255 ]
    topic3 42.8571 [ 3 / 4 ]