11

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

??

4 Answers 4

25

Just a simple sed command will do the job:

sed 's/[^0-9]//g' file.txt

OUTPUT

3
34
3
Sign up to request clarification or add additional context in comments.

3 Comments

What is the case for fractional number eg: 123.43 ?
Since question was extracting integer so this was answer for that. For floating point a different solution is needed.
It is not appropriate to answer a new question from comment section. If you post a question then I will surely try to answer.
13

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.

1 Comment

This doesn't take into consideration there might be other non-alphanumeric characters in the given string, such as ()[]{}#$!. etc. Shouldn't it better read echo ${xyz//[^0-9]/} instead for extracting "nothing but integers"?
8

How about using tr?

for s in ABC3 DFGSS34 CVBB3 ; do
    tr -cd 0-9 <<<"$s"
    echo
done

Comments

7

What about a grep version?

grep -o '[0-9]*' file.txt

3 Comments

grep -o '[0-9][0-9]*' file.txt
@Mahdi: For this particular use case that's not necessary. But in general you are right.
why not grep -o "[0-9]\+" instead of grep -o '[0-9][0-9]*'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.