LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shell script -- Convert string to number for subtraction (https://www.linuxquestions.org/questions/linux-newbie-8/shell-script-convert-string-to-number-for-subtraction-4175458799/)

BlackWhite 04-19-2013 03:28 PM

Shell script -- Convert string to number for subtraction
 
Hi! I'm totally a newbie to shell scripting. I'm trying to calculate the difference between 2 numbers which grepped from a file, which gave me error because I guess they are of type string, not numeric:

var1=timestamp:n:1111111.2222222
var2=timestamp:n:3333333.4444444

start_time=$(echo ${var1#timestamp:n:}
stop_time=$(echo ${var2#timestamp:n:}

render_time=`expr $stop_time - $start_time`
which gave me error

Please help! Thanks!

jpollard 04-19-2013 03:53 PM

I believe bash only handles integers.

You might try using perl or python instead.

The conversion from string to numbers is automatic, as determined by the operator being applied to the values.

David the H. 04-21-2013 01:59 PM

Please use ***[code][/code]*** tags around your code and data, to preserve the original formatting and to improve readability. Do not use quote tags, bolding, colors, "start/end" lines, or other creative techniques.


Yes, bash is integer only, as is expr, which is what you're trying to use.

(expr is completely unneeded in modern shells, btw. Everything it can do is available built in. I suggest just forgetting that it exists. ;))

For floating point arithmetic you need to use an external command like bc or awk.

arithmetic expressions
How can I calculate with floating point numbers instead of just integers?


You also have two completely unnecessary uses of echo (the commands for which were unclosed as well),
and $(..) is highly recommended over `..`.

Code:

var1=timestamp:n:1111111.2222222
var2=timestamp:n:3333333.4444444

start_time=${var1#*:n:}
stop_time=${var2#*:n:}

render_time=$( echo "$stop_time - $start_time" | bc )

echo "$stop_time - $start_time = $render_time"



All times are GMT -5. The time now is 09:07 PM.