Linux 如何在 UNIX 中将字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11268437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:10:13  来源:igfitidea点击:

How to convert string to integer in UNIX

linuxshellunixinteractive

提问by qwarentine

I have d1="11"and d2="07". I want to convert d1and d2to integers and perform d1-d2. How do I do this in UNIX?

我有d1="11"d2="07"。我想将d1和转换d2为整数并执行d1-d2. 我如何在 UNIX 中执行此操作?

d1 - d2currently returns "11-07"as result for me.

d1 - d2目前"11-07"为我返回结果。

采纳答案by William Pursell

The standard solution:

标准解决方案:

 expr $d1 - $d2

You can also do:

你也可以这样做:

echo $(( d1 - d2 ))

but beware that this will treat 07as an octal number! (so 07is the same as 7, but 010is different than 10).

但请注意,这将被07视为八进制数!(so07与 相同7,但010不同于10)。

回答by qwarentine

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.

等等。

回答by Levon

Any of these will work from the shell command line. bcis probably your most straight forward solution though.

其中任何一个都可以在 shell 命令行中工作。bc不过,这可能是您最直接的解决方案。

Using bc:

使用bc

$ echo "$d1 - $d2" | bc

Using awk:

使用awk

$ echo $d1 $d2 | awk '{print  - }'

Using perl:

使用perl

$ perl -E "say $d1 - $d2"

Using Python:

使用Python

$ python -c "print $d1 - $d2"

all return

全部返回

4

回答by mykeaka

let d=d1-d2;echo $d;

This should help.

这应该有帮助。

回答by Bruno Bronosky

An answer that is not limited to the OP's case

不限于OP案例的答案

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.

问题的标题将人们引到这里,因此我决定为其他所有人回答这个问题,因为 OP 描述的案例非常有限。

TL;DR

TL; 博士

I finally settled on writing a function.

我终于决定写一个函数。

  1. If you want 0in case of non-int:
  1. 如果你想0在非整数的情况下:
int(){ printf '%d' ${1:-} 2>/dev/null || :; }
  1. If you want [empty_string]in case of non-int:
  1. 如果你想要[empty_string]在非整数的情况下:
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
  1. If you want find the first int or [empty_string]:
  1. 如果你想找到第一个 int 或[empty_string]
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
  1. If you want find the first int or 0:
  1. 如果你想找到第一个 int 或 0:
# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }

If you want to get a non-zero status code on non-int, remove the ||:(aka or true) but leave the ;

如果您想在非整数上获得非零状态代码,请删除||:(又名或true)但保留;

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 "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }

    int(){ printf '%d' ${1:-} 2>/dev/null||:; };
    test

    int(){ expr 0 + ${1:-} 2>/dev/null||:; }
    test

    int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
    test

    int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }
    test

    # unexpected inconsistent results from `bc`
    int(){ bc<<<"${1:-}" 2>/dev/null||:; }
    test
)

Test output

测试输出

int is a function
int ()
{
    printf '%d' ${1:-} 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 + ${1:-} 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 ${1:-} : '[^0-9]*\([0-9]*\)' 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 ${1:-} : '[^0-9]*\([0-9]*\)' 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 <<< "${1:-}" 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 answeris not compatible with set -o nounset(aka set -u)

我被送进了这个兔子洞,因为接受的答案set -o nounset(又名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