如何从字符串中提取数字? [英] How to extract numbers from a string?

查看:105
本文介绍了如何从字符串中提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串包含路径

string="toto.titi.12.tata.2.abc.def"

我只想从该字符串中提取数字.

I want to extract only the numbers from this string.

要提取第一个数字:

tmp="${string#toto.titi.*.}"
num1="${tmp%.tata*}"

要提取第二个数字:

tmp="${string#toto.titi.*.tata.*.}"
num2="${tmp%.abc.def}"

所以要提取一个参数,我必须分两步完成.如何一步一步提取数字?

So to extract a parameter I have to do it in 2 steps. How to extract a number with one step?

推荐答案

您可以使用tr删除所有非数字字符,如下所示:

You can use tr to delete all of the non-digit characters, like so:

echo toto.titi.12.tata.2.abc.def | tr -d -c 0-9

这篇关于如何从字符串中提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆