Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract integer from string using bash

I tried to find the solution here but could not; given strings like

ABC3
DFGSS34
CVBB3

how do I extract the integers so I get

3
34
3

??

like image 483
Open the way Avatar asked Jun 17 '11 15:06

Open the way


People also ask

What is %d in bash?

In bash command -d is to check if the directory exists or not. For example, I having a directory called. /home/sureshkumar/test/. The directory variable contains: "/home/sureshkumar/test/"

How do I convert a string to a number in bash?

Alternate method: use expr You can also use the expr tool to do the evaluation, but do note that it is not a “native” Bash procedure, as you need to have coreutils installed (by default on Ubuntu) as a separate package. I hope this quick little tutorial helped you in evaluating bash strings as numbers.


1 Answers

For a bash-only solution, you can use parameter patter substition:

pax$ xyz=ABC3 ; echo ${xyz//[A-Z]/}
3
pax$ xyz=DFGSS34 ; echo ${xyz//[A-Z]/}
34
pax$ xyz=CVBB3 ; echo ${xyz//[A-Z]/}
3

It's very similar to sed solutions but has the advantage of not having to fork another process. That's probably not important for small jobs but I've had situations where this sort of thing was done to many, many lines of a file and the non-forking is a significant speed boost.

like image 143
paxdiablo Avatar answered Oct 13 '22 12:10

paxdiablo