- How to convert string to integer in UNIX shelll
- 5 Answers 5
- An answer that is not limited to the OP’s case
- TL;DR
- Tests
- Test output
- Note
- How to Evaluate Strings as Numbers in Bash
- Converting string variables to numbers
- Try mixing actual strings and numbers
- Alternate method: use expr
- How to convert string to integer in unix in Linux?
- Method 1: Using the atoi() function
- Method 2: Using the strtol() function
- Conclusion
- In bash shell script how do I convert a string to an number [duplicate]
- Linked
- Related
- Hot Network Questions
How to convert string to integer in UNIX shelll
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.
5 Answers 5
but beware that this will treat 07 as an octal number! (so 07 is the same as 7 , but 010 is different than 10 ).
Given that bash has syntax for specifying numeric base, why not demonstrate it here (albeit with a portability caveat)?
Given that bash is NOT the standard and isn’t guaranteed on all targets. how about skipping the bash-isms since they didn’t ask how to do it in bash.
Be careful if your variables can hold non-integer strings or if you are using options nounset and errexit (which you should always use). I have written many tests for different scenarios in my answer stackoverflow.com/a/59781257/117471
You should definitely be wary of non-integer values, and using nounset is often a good idea. But you should never use errexit .
Any of these will work from the shell command line. bc is probably your most straight forward solution though.
Not sure if it is a bug or a feature of expr , awk , bc , and dc , but all of those tools handle the case d1=09 by treating 09 as the decimal value 9. However, perl and python treat it as a syntax error. You get different results for the case d1=010
An answer that is not limited to the OP’s case
The title of the question leads people here, so I decided to answer that question for everyone else since the OP’s described case was so limited.
TL;DR
I finally settled on writing a function.
# This is a combination of numbers 1 and 2 int() < expr $: '[^0-9]*\(4*\)' 2>/dev/null||:; >
If you want to get a non-zero status code on non-int, remove the ||: (aka or true ) but leave the ;
Tests
# Wrapped in parens to call a subprocess and not `set` options in the main bash process # In other words, you can literally copy-paste this code block into your shell to test ( set -eu; tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" ) test()< echo; type int; for test in "$"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; > int() < printf '%d' $2>/dev/null||:; >; test int() < expr 0 + $2>/dev/null||:; > test int() < expr $: '[^0-9]*\(6*\)' 2>/dev/null||:; > test int() < printf '%d' $(expr $: '[^0-9]*\(7*\)' 2>/dev/null)||:; > test # unexpected inconsistent results from `bc` int()< bc<<<"$" 2>/dev/null||:; > test )
Test output
int is a function int () < printf '%d' $2> /dev/null || : > got '4' from '4' got '5' from '5' got '0' from '6foo' got '0' from 'bar7' got '0' from 'foo8.9bar' got '0' from 'baz' got '0' from ' ' got '0' from '' got '0' with no argument int is a function int () < expr 0 + $2> /dev/null || : > got '4' from '4' got '5' from '5' got '' from '6foo' got '' from 'bar7' got '' from 'foo8.9bar' got '' from 'baz' got '' from ' ' got '' from '' got '' with no argument int is a function int () < expr $: '[^0-9]*\(6*\)' 2> /dev/null || : > got '4' from '4' got '5' from '5' got '6' from '6foo' got '7' from 'bar7' got '8' from 'foo8.9bar' got '' from 'baz' got '' from ' ' got '' from '' got '' with no argument int is a function int () < printf '%d' $(expr $: '[^0-9]*\(5*\)' 2>/dev/null) || : > got '4' from '4' got '5' from '5' got '6' from '6foo' got '7' from 'bar7' got '8' from 'foo8.9bar' got '0' from 'baz' got '0' from ' ' got '0' from '' got '0' with no argument int is a function int () < bc <<< "$" 2> /dev/null || : > got '4' from '4' got '5' from '5' got '' from '6foo' got '0' from 'bar7' got '' from 'foo8.9bar' got '0' from 'baz' got '' from ' ' got '' from '' got '' with no argument
Note
I got sent down this rabbit hole because the accepted answer is not compatible with set -o nounset (aka set -u )
# This works $ ( number="3"; string="foo"; echo $((number)) $((string)); ) 3 0 # This doesn't $ ( set -u; number="3"; string="foo"; echo $((number)) $((string)); ) -bash: foo: unbound variable
How to Evaluate Strings as Numbers in Bash
Learn how to evaluate bash strings as integers to perform successful arithmetic operations.
Like everything is file in Linux, everything is string in bash.
Yes! Technically, there are no data types in Bash. Essentially, Bash variables are just character strings.
And that creates a problem when you are trying to do arithmetic operations in bash. The numbers you try to add give you weird results.
[email protected]:~$ sum=3+6 [email protected]:~$ echo $sum 3+6
To convert strings to integers in bash, wrap them in $((X)). Like this:
If the string has an identifiable number, it will be treated as a number. The example I showed above can be corrected as:
[email protected]:~$ sum=$((3+6)) [email protected]:~$ echo $sum 9
Let’s see the conversion of strings into numbers in a bit more detail so that you can use arithmetic calculations in bash.
Converting string variables to numbers
Let’s declare some «numbers» which are basically strings of characters.
You can check the assigned number:
[email protected]:~$ echo $a 11 [email protected]:~$ echo $b 3
Let’s now try to add both numbers and store the value in a third variable c :
[email protected]:~$ c=$a+$b [email protected]:~$ echo $c 11+3
As you can see on the output above, c is also being treated as a string.
To make the addition successful, you need to “convert” it through an arithmetic expansion:
[email protected]:~$ c=$(($a+$b)) [email protected]:~$ echo $c 14
Do note that c is still actually a string, until you implicitly use the same arithmetic expansion again for another operation that I’ll discuss in a while.
The above is equivalent to:
Let’s use a third variable d for another operation:
All these implicit declarations are still strings. It is same as how I had defined a and b earlier.
Now for the second operation:
[email protected]:~$ e=$(($a+$b*$c-$d)) [email protected]:~$ echo $e 16
In the above expression, the product of b and c is calculated first and finally the addition and subtraction follow.
As I mentioned previously, anything you do between $((. )) is considered to be an arithmetic operation.
All this conversion works for integers. It won’t work with floating points i.e. numbers with decimal points.
Try mixing actual strings and numbers
Mixing strings and integers is still safer than mixing coke and mint. It does produce a weird result, though.
[email protected]:~$ sum=$((3+hello)) [email protected]:~$ echo $sum 3
It will only work when there are numbers (as string). If it is pure character string, it won’t be magically converted into some numbers. Instead, it is ignored as you can see in the example above.
Alternate method: use expr
You can also use the expr tool to do the evaluation, but do note that it is not a “native” Bash procedure, as you need to have coreutils installed (by default on Ubuntu) as a separate package.
I hope this quick little tutorial helped you in evaluating bash strings as numbers. If you have questions or suggestions, feel free to leave a comment below.
How to convert string to integer in unix in Linux?
There are several ways to convert a string to an integer in UNIX, but some of the most common methods include using the atoi() function and the strtol() function. Here is an overview of how to use these functions, along with some examples to illustrate their usage.
Method 1: Using the atoi() function
The atoi() function is a built-in function in the C standard library that can be used to convert a string of characters to an integer. It takes a single argument, which is the string that you want to convert. Here is an example of how to use the atoi() function:
#include #include int main() char str[] = "123"; int num; num = atoi(str); printf("The integer value of %s is %d\n", str, num); return 0; >
In this example, we first declare a string variable called str and assign it the value «123». Next, we declare an integer variable called num and assign it the value returned by the atoi() function when it is passed str as an argument. Finally, we use the printf() function to print out the original string and its corresponding integer value.
Method 2: Using the strtol() function
The strtol() function is another built-in function in the C standard library that can be used to convert a string of characters to an integer. It takes three arguments: the string that you want to convert, a pointer to a variable that will hold the converted value, and the base of the number represented in the string. Here is an example of how to use the strtol() function:
#include #include int main() char str[] = "123"; char *endptr; long num; num = strtol(str, &endptr, 10); printf("The integer value of %s is %ld\n", str, num); return 0; >
In this example, we first declare a string variable called str and assign it the value «123». Next, we declare a pointer variable called endptr and a long integer variable called num . The strtol() function is called and passed str , endptr and 10 as arguments. The strtol() function converts the string in str to a long integer and stores the result in num . The strtol() function also sets the value of endptr to the first invalid character in the string. Finally, we use the printf() function to print out the original string and its corresponding integer value.
It’s important to note that the atoi() and strtol() functions do not check for overflow or underflow, so it is important to check for these conditions before using the returned value.
or underflow, so it is important to check for these conditions before using the returned value.
Another method to convert string to integer is using the sscanf() function. The sscanf() function is similar to the scanf() function but it reads the input from a string instead of the standard input. Here is an example of how to use the sscanf() function:
#include int main() char str[] = "123"; int num; sscanf(str, "%d", &num); printf("The integer value of %s is %d\n", str, num); return 0; >
In this example, we first declare a string variable called str and assign it the value «123». Next, we declare an integer variable called num . The sscanf() function is called and passed str and the format specifier «%d» as arguments. The sscanf() function reads the string in str and converts it to an integer according to the format specifier, and store the result in num . Finally, we use the printf() function to print out the original string and its corresponding integer value.
Another method is using the strtoul() function which is similar to the strtol() but it returns an unsigned long int instead of long int.
It’s worth noting that all these functions only convert the initial portion of the string to an integer. If the string contains any non-numeric characters after the first numeric characters, they will be ignored. It’s also worth noting that the atoi() and strtol() functions will return zero if the input string is not a valid number.
Conclusion
In conclusion, converting a string to an integer in UNIX is a common task that can be achieved using various built-in functions such as atoi() , strtol() , sscanf() and strtoul() . Each of these functions has its own advantages and disadvantages, and it is important to choose the right one based on your specific needs. It’s important to note that all these functions only convert the initial portion of the string to an integer and also these functions do not check for overflow or underflow, so it is important to check for these conditions before using the returned value. It is important to understand the concepts and mechanics of each function before implementing them in your code.
In bash shell script how do I convert a string to an number [duplicate]
If your values are guaranteed to be in the same form and range, you can do string comparisons:
if [[ $x > 0.70 ]] then echo "It's true" fi
This will fail if x is «.8» (no leading zero), for example.
However, while Bash doesn’t understand decimals, its builtin printf can format them. So you could use that to normalize your values.
$ x=.8 $ x=$(printf %.2 $x) $ echo $x 0.80
For some reason, this solution appeals to me:
if ! echo "$x $y -p" | dc | grep > /dev/null ^-; then echo "$x > $y" else echo "$x < $y" fi
You'll need to be sure that $x and $y are valid (eg contain only numbers and zero or one '.') and, depending on how old your dc is, you may need to specify something like '10k' to get it to recognize non-integer values.
Here is my simple solution:
BaseLine=70.0 if [ $string \> $BaseLine ] then echo $string else echo "TOO SMALL" fi
x="0.80" y="0.70" result=$(awk -vx=$x -vy=$y 'BEGIN< print x>=y?1:0>') if [ "$result" -eq 1 ];then echo "x more than y" fi
Very cleaver. Works better than bc. It allowed me to use variables, which was a requirement, not static numbers. Thank you. Simple and clear. I had to learn bc to use it, needed a quick and easy solution! Thank you!
The bash language is best characterized as a full-featured macro processor, as such there is no difference between numbers and strings. The problem is that test(1) works on integers.
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.