saadurr
saadurr

Reputation: 77

Bash: Floating point calculations in bash script

I am using the following script to read some numbers and calculate their average. However, it seems that floating point calculations cannot be performed like this.

hours=0
#echo "\n" >> user-list.txt
while IFS=, read -r col1 col2 col3 col4 col5 col6 col7 || [[ -n $col1 ]]
do
    ((hours = hours + col5))
    #echo "$col1, $col2"
done < <(tail -n+2 user-list.txt)

((hours = hours/10))
echo "$hours" > wednesday.txt

How can I perform floating point calculations in this script?

Below is a sample of the input file:

Computer ID,User ID,M,T,W,T,F
Computer1,User3,5,7,3,5,2
Computer2,User5,8,8,8,8,8
Computer3,User4,0,8,0,8,4
Computer4,User1,5,4,5,5,8

TIA

Upvotes: 0

Views: 191

Answers (2)

Raman Sailopal
Raman Sailopal

Reputation: 12877

awk -F, 'NR > 1 { hours+=$5 } END { printf "%.2f",hours/10 }' <user-list.txt > wednesday.txt

Using awk, set comma as the field delimiter and then redirect user-list.txt into awk. For each line, set hours to hours plus the fifth comma separated value. At the end, divide hours by 10 and print to 2 decimal places. Redirect the output back out to wednesday.txt.

Upvotes: 0

Bodo
Bodo

Reputation: 9855

This awk script will process the data and calculate the result.

awk -F, 'FNR>1 { hours += $5 } END { print hours/10; }' user-list.txt

Of course you can redirect the output to a file.

awk -F, 'FNR>1 { hours += $5 } END { print hours/10; }' user-list.txt > wednesday.txt

Explanation:

-F, specify , as field separator
FNR>1 condition to skip first line of every file (the column names)
{ hours += $5 } sum up 5th column
END { print hours/10; } at the end print the result

The script allows to process more than one file like this:

awk -F, 'FNR>1 { hours += $5 } END { print hours/10; }' file1 file2 file3 [...] > outputfile

Upvotes: 1

Related Questions