How can subtract 2 floats which have been extracted from 2 other files with BASH
13,863
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"
Related videos on Youtube
Comments
-
3kstc over 1 year
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")
-
3kstc over 9 yearsNow 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!
-
jimmij over 9 years@3kstc I understand that you don't have
bc
, but solution withawk
doesn't work either? You can assign output to variable with command substitution$()
:difference=$(awk '{print $1-$2}' <<< "$new $old")
-
3kstc over 9 yearsit works! many thanks! difference=$(awk '{print $1-$2}' <<< "$new $old") did the trick!
-
3kstc over 9 yearsNow I have another problem; How can I use
$difference
in anif
statement?if [ "$difference" -ge "$limit"]; then echo "email sent out" fi
It doesn't like that I'm using afloat
in the condition, how could I bypass this? -
3kstc over 9 years[solved] used
int_difference=${difference%.*}