问题
I have d1="11"
and d2="07"
. I want to convert d1
and d2
to integers and perform d1-d2
. How do I do this in UNIX?
d1 - d2
currently returns "11-07"
as result for me.
回答1:
The standard solution:
expr $d1 - $d2
You can also do:
echo $(( d1 - d2 ))
but beware that this will treat 07
as an octal number! (so 07
is the same as 7
, but 010
is different than 10
).
回答2:
Any of these will work from the shell command line. bc
is probably your most straight forward solution though.
Using bc:
$ echo "$d1 - $d2" | bc
Using awk
:
$ echo $d1 $d2 | awk '{print $1 - $2}'
Using perl
:
$ perl -E "say $d1 - $d2"
Using Python
:
$ python -c "print $d1 - $d2"
all return
4
回答3:
let d=d1-d2;echo $d;
This should help.
回答4:
Use this:
#include <stdlib.h>
#include <string.h>
int main()
{
const char *d1 = "11";
int d1int = atoi(d1);
printf("d1 = %d\n", d1);
return 0;
}
etc.
来源:https://stackoverflow.com/questions/11268437/how-to-convert-string-to-integer-in-unix