Bash - 从字符串中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10579941/
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
Bash - Extract numbers from String
提问by user1360250
I got a string which looks like this:
我得到了一个看起来像这样的字符串:
"abcderwer 123123 10,200 asdfasdf iopjjop"
“abcderwer 123123 10,200 asdfasdf iopjjop”
Now I want to extract numbers, following the scheme xx,xxx where x is a number between 0-9. E.g. 10,200. Has to be five digit, and has to contain ",".
现在我想提取数字,遵循方案 xx,xxx 其中 x 是 0-9 之间的数字。例如 10,200。必须是五位数字,并且必须包含“,”。
How can I do that?
我怎样才能做到这一点?
Thank you
谢谢
回答by codaddict
You can use grep:
您可以使用grep:
$ echo "abcderwer 123123 10,200 asdfasdf iopjjop" | egrep -o '[0-9]{2},[0-9]{3}'
10,200
回答by Paused until further notice.
In pure Bash:
在纯 Bash 中:
pattern='([[:digit:]]{2},[[:digit:]]{3})'
[[ $string =~ $pattern ]]
echo "${BASH_REMATCH[1]}"
回答by keyser
Check out pattern matching and regular expressions.
查看模式匹配和正则表达式。
Links:
链接:
and as mentioned above, one way to utilize pattern matching is with grep. Other uses: echo supports patterns (globbing) and find supports regular expressions.
如上所述,使用模式匹配的一种方法是使用 grep。其他用途:echo 支持模式(globbing)并且 find 支持正则表达式。
回答by tripleee
Simple pattern matching (glob patterns) is built into the shell. Assuming you have the strings in $*(that is, they are command-line arguments to your script, or you have used seton a string you have obtained otherwise), try this:
简单的模式匹配(glob 模式)内置在 shell 中。假设你有字符串$*(也就是说,它们是你脚本的命令行参数,或者你已经用set其他方式获得的字符串),试试这个:
for token; do
case $token in
[0-9][0-9],[0-9][0-9][0-9] ) echo "$token" ;;
esac
done
回答by bos
The following example using your input data string should solve the problem using sed.
以下使用输入数据字符串的示例应该可以解决使用 sed 的问题。
$ echo abcderwer 123123 10,200 asdfasdf iopjjop | sed -ne 's/^.*\([0-9,]\{6\}\).*$//p'
10,200
回答by William Pursell
A slightly non-typical solution:
一个稍微不典型的解决方案:
< input tr -cd [0-9,\ ] | tr \ '2' | grep '^..,...$'
(The first tr removes everything except commas, spaces, and digits. The second tr replaces spaces with newlines, putting each "number" on a separate line, and the grep discards everything except those that match your criterion.)
(第一个 tr 删除除逗号、空格和数字以外的所有内容。第二个 tr 用换行符替换空格,将每个“数字”放在单独的行上,grep 丢弃除符合您的标准的所有内容之外的所有内容。)

