Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to integer in UNIX

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.

like image 921
qwarentine Avatar asked Jun 29 '12 20:06

qwarentine


People also ask

Can you convert a string into a number?

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.

What command will convert strings to integers?

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.

How do you typecast in Linux?

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.


2 Answers

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).

like image 114
William Pursell Avatar answered Sep 21 '22 19:09

William Pursell


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 
like image 27
Levon Avatar answered Sep 22 '22 19:09

Levon