3

I'm trying to get the difference between two numbers which I have taken from two files. I think my code will make sense:

I've tried to make it work by two different methods, didn't work. What I get as an output is zero (0).

#method 1
difference_btwn_eng_hrs_MX3_122=$(($(sed -n '1p' engine_hours_new_MX3_122.txt)-$(sed -n '1p' engine_hours_old_MX3_122.txt)))
echo "$difference_btwn_eng_hrs_MX3_122"

#method 2
new=$(sed -n '1p' engine_hours_new_MX3_122.txt)
old=$(sed -n '1p' engine_hours_old_MX3_122.txt)
echo "$new $old" | awk '{print $new - $old}'

Eventually I will use the difference to set intervals for email updates.

The values inside the files are 511.786 (new) and 509.768 (old), and the error I get from the terminal is as follows:

line 40: 511.786-509.765: syntax error: invalid arithmetic operator (error token is ".786-509.765")
0

1 Answer 1

14

The problem with first example is that bash can operate only on integers and your second attempt with awk is simply not correct.

I propose to use bc for this job:

bc <<< "$new-$old"

<<< is so called here string, and it is basically the shorter form echo "$new-$old" | bc.

You can also modify your awk command if you like:

echo "$new $old" | awk '{print $1-$2}'

or (using here string as above):

awk '{print $1-$2}' <<< "$new $old"
5
  • Now the error has changed "bc: command not found". I've tried both of your suggestions. But no luck. Additionally with the calculation how would I assign it to a variable "difference", would it be difference="$new-$old" | bc, or difference=$new-$old | bc ? Any help is truly appreciated!
    – 3kstc
    Commented Feb 12, 2015 at 1:43
  • 2
    @3kstc I understand that you don't have bc, but solution with awk doesn't work either? You can assign output to variable with command substitution $(): difference=$(awk '{print $1-$2}' <<< "$new $old")
    – jimmij
    Commented Feb 12, 2015 at 1:47
  • it works! many thanks! difference=$(awk '{print $1-$2}' <<< "$new $old") did the trick!
    – 3kstc
    Commented Feb 12, 2015 at 1:53
  • Now I have another problem; How can I use $difference in an ifstatement? if [ "$difference" -ge "$limit"]; then echo "email sent out" fi It doesn't like that I'm using a float in the condition, how could I bypass this?
    – 3kstc
    Commented Feb 12, 2015 at 3:14
  • [solved] used int_difference=${difference%.*}
    – 3kstc
    Commented Feb 12, 2015 at 3:32

Not the answer you're looking for? Browse other questions tagged .