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.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
Let's have a simple illustration of implicit type casting in our Linux system to demonstrate the working of typecasting. So open the command line terminal in the Linux system after logging in. Use “Ctrl+Alt+T” for a quick opening. The GNU editor has been used to write C code so create a quick C language file “one.
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
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With