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")
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
3kstc
  • 4,616
  • 15
  • 33
  • 49

1 Answers1

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"
jimmij
  • 46,064
  • 19
  • 123
  • 136
  • 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 Feb 12 '15 at 01: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 Feb 12 '15 at 01:47
  • it works! many thanks! difference=$(awk '{print $1-$2}' <<< "$new $old") did the trick! – 3kstc Feb 12 '15 at 01:53
  • Now I have another problem; How can I use `$difference` in an `if`statement? `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 Feb 12 '15 at 03:14
  • [solved] used `int_difference=${difference%.*}` – 3kstc Feb 12 '15 at 03:32