UNIX BASH:从字符串中提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569754/
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-09-17 22:31:33  来源:igfitidea点击:

UNIX BASH: extracting number from string

stringbashunix

提问by Albinoswordfish

This is probably a very simple question to an experienced person with UNIX however I'm trying to extract a number from a string and keep getting the wrong result.

对于有 UNIX 经验的人来说,这可能是一个非常简单的问题,但是我试图从字符串中提取一个数字并不断得到错误的结果。

This is the string:

这是字符串:

8962 ? 00:01:09 java

This it the output I want

这是我想要的输出

8962

But for some reason I keep getting the same exact string back. This is what I've tried

但出于某种原因,我一直在取回完全相同的字符串。这是我试过的

pid=$(echo $str | sed "s/[^[0-9]{4}]//g")

If anybody could help me out it would be appreciated.

如果有人可以帮助我,将不胜感激。

回答by Peter Tillemans

There is more than one way to skin a cat :

给猫剥皮的方法不止一种:

pti@pti-laptop:~$ echo 8962 ? 00:01:09 java | cut -d' ' -f1
8962
pti@pti-laptop:~$ echo 8962 ? 00:01:09 java | awk '{print }'
8962

cut cuts up a line in different fields based on a delimeter or just byte ranges and is often useful in these tasks.

cut 根据分隔符或仅字节范围在不同字段中剪切一行,并且在这些任务中通常很有用。

awk is an older programming language especially useful for doing stuff one line at a time.

awk 是一种较旧的编程语言,特别适用于一次一行地做事情。

回答by ghostdog74

Shell, no need to call external tools

Shell,无需调用外部工具

$ s="8962 ? 00:01:09 java"
$ IFS="?"
$ set -- $s
$ echo 
8962

回答by Paused until further notice.

Pure Bash:

纯重击:

string='8962 ? 00:01:09 java'
pid=${string% \?*}

Or:

或者:

string='8962 ? 00:01:09 java'
array=($string)
pid=${array[0]}

回答by Sean

I think this is what you want:

我想这就是你想要的:

pid=$(echo $str | sed 's/^\([0-9]\{4\}\).*//')

回答by Fritz G. Mehner

Pure Bash:

纯重击:

string="8962 ? 00:01:09 java"

[[ $string =~ ^([[:digit:]]{4}) ]]

pid=${BASH_REMATCH[1]}

回答by Crayon Violent

/^[0-9]{4}/matches 4 digits at the beginning of the string

/^[0-9]{4}/匹配字符串开头的 4 位数字