Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numbers from a string?

Tags:

I have string contains a path

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

I want to extract only the numbers from this string.

To extract the first number:

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

To extract the second number:

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?

like image 548
MOHAMED Avatar asked Jul 26 '13 14:07

MOHAMED


People also ask

How do I extract numbers from a string in Excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string. Note that since the workbook now has VBA code in it, you need to save it with .


1 Answers

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
like image 70
mti2935 Avatar answered Oct 08 '22 20:10

mti2935