0

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

5
  • Maybe use awk to process your data. It can do floating point calculation. Commented Nov 20, 2020 at 12:26
  • Use awk. You will need less code also. Commented Nov 20, 2020 at 12:26
  • Please edit your question and show an example file user-list.txt. This will allow us to test a proposed solution. Commented Nov 20, 2020 at 12:27
  • @Bodo I have added a sample of the input file. Commented Nov 20, 2020 at 12:45
  • @SaadUrRehman : Use zsh. It can do floats. Commented Nov 20, 2020 at 13:56

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.