LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   simple bash script problem with division. (http://www.linuxquestions.org/questions/linux-software-2/simple-bash-script-problem-with-division-680341/)

hockeyman_102 10-31-2008 04:01 PM

simple bash script problem with division.
 
Hi all. This is a simple bash script that i've spent way too much time on, I'm tying to get a few stats from a group of files. Basically there is a group of files per day (i.e. today = 20081031-0.txt to 20081031-9.txt) and they vary, but I want to check these logs to see how many times we are hitting a .com, .net, etc.. The "percent" is where I'm having issues... It's not really a big deal, but I figured I'd post it. This will be run on FreeBSD btw, if it matters.
Thanks in advance!

Code:

#!/bin/bash
#  liststats.sh
#  Parse daily logs for .com, .net, .org (to start) and push to stats.csv

year=`date +%Y`
month=`date +%m`
day=`date +%d`
day=30    # I did this because the logs for today aren't done.

if [ -e /usr/local/$year$month$day-0.txt ]; then

    total=`cat /usr/local/$year$month$day-?.txt | wc -l | sed 's/ //g'`

    echo "" > stats.csv
    for i in ".com" ".net" ".org";
    do                        # had to use sed to strip the whitespace in hopes it would work...
        count=`cat /usr/local/$year$month$day-?.txt | grep -i $i | wc -l | sed 's/ //g'`
        #percent=$(($count/$total))    # everything else seems to work, but this!
        let "percent = $count / $total"
        echo "$i,$count,$percent,$total >> stats.csv"
        #echo "$i,$count,$percent" >> stats.csv
    done   
else       
    echo "$year$month$day-0.txt not found in /usr/local/"
fi

The desired result (for example):
.com,200,80.00
.net,85,34.00
.org,20,8.00

MarkByers 10-31-2008 04:08 PM

percent=$(($count*100/$total))

If you want fraction then use "bc":

percent=`echo $count*100/$total | bc -l`

pwc101 10-31-2008 04:10 PM

bash's internal maths can't do floating point calculations; you're best off using bc, which can to a specified number of digits.

edit: too slow by half! :)


All times are GMT -5. The time now is 12:16 PM.