Convert Floating Point Number To Integer Via File Read

295 Views Asked by At

I'm trying to get this to work when the "line" is in the format ###.###

Example line of data:

Query_time: 188.882

Current script:

#!/bin/bash

while read line; do
    if [ $(echo "$line" | cut -d: -f2) -gt 180 ];
    then
        echo "Over 180"
    else
        echo "Under 180"
    fi
done < test_file

Errors I get:

./calculate: line 4: [: 180.39934: integer expression expected
2

There are 2 best solutions below

0
On BEST ANSWER

You can use this awk:

$ echo Query_time: 188.882 | awk '{ print ($2>180?"Over ":"Under ") 180 }'
Over 180

It takes the second space delimited field ($2) and using conditional operator outputs if it was over or under (less than or equal to) 180.

1
On

If you have:

line='Query_time: 188.882'

This expression:

$(echo "$line" | cut -d: -f2) -gt 180

Will give an error invalid arithmetic operator since BASH cannot handle floating point numbers.

You can use this awk command:

awk -F ':[ \t]*' '{print ($2 > 180 ? "above" : "under")}' <<< "$line"
above