sed extract digits

Ned picture Ned · Sep 12, 2011 · Viewed 24.8k times · Source

I try to extract digits with sed:

echo hgdfjg678gfdg kjg45nn | sed 's/.*\([0-9]\+\).*/\1/g'

but result is: 5 How to extract: 678 and 45? Thanks in advance!

Answer

hmakholm left over Monica picture hmakholm left over Monica · Sep 12, 2011

The problem is that the . in .* will match digits as well as non-digits, and it keeps on matching as long as it can -- that is as long as there's one digit left unconsumed that can match the [0-9].

Instead of extracting digits, just delete non-digits:

echo hgdfjg678gfdg kjg45nn | sed 's/[^0-9]//g'

or even

echo hgdfjg678gfdg kjg45nn | tr -d -c 0-9