Open the way
Open the way

Reputation: 27329

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

??

Upvotes: 11

Views: 37285

Answers (4)

bmk
bmk

Reputation: 14137

What about a grep version?

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

Upvotes: 7

sorpigal
sorpigal

Reputation: 26086

How about using tr?

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

Upvotes: 8

paxdiablo
paxdiablo

Reputation: 881113

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.

Upvotes: 13

anubhava
anubhava

Reputation: 784918

Just a simple sed command will do the job:

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

OUTPUT

3
34
3

Upvotes: 25

Related Questions