Reputation: 67
i have file with the following data records:
0.005
0.027
0.352
1.005
0.117
0.752
I'm trying to read the file using bash line by line and count the numbers into 3 groups:
if [($num < 0.2)] then min++
if [($num > 0.2) && ($num < 1)] then med++
if [($num > 1)] then max++
At the end I need to print out the 3 variable to file which count all the records. Any idea how to read the file in bash and manipulating it using float in bash?
Upvotes: 0
Views: 373
Reputation: 22012
If you want to do it with bash
by all means, possible workaround will
be to multiply the numbers by 1,000 (or whatever appropriate) and treat
them as integers. How about:
while read -r x; do
num=$((10#$(printf "%.3f" "$x" | tr -d ".")))
# echo "$num"
(( num < 200 )) && (( min++ ))
(( num > 200 && num < 1000 )) && (( med++ ))
(( num > 1000 )) && (( max++ ))
done < "data.txt"
printf "min=%d med=%d max=%d\n" "$min" "$med" "$max"
As @dibery comments, you need to decide how to handle exact 0.2 and 1.
Upvotes: 0
Reputation: 3460
Unfortunately, bash doesn't like floating numbers very much; however, you may use other text processing tools like awk
:
awk '{if($0 < 0.2)min++; else if($0 < 1)med++; else max++;} END {print min, med, max;}' file.txt
Also please note that your algorithm doesn't handle numbers exactly at 0.2 and 1.
Upvotes: 1