Sed extraction digits

I am trying to extract numbers using sed:

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

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

+7
source share
4 answers

The problem is that . in .* will correspond to numbers as well as numbers, and it will continue until it is possible - this is until one digit is lost, which may coincide [0-9] .

Instead of extracting the numbers, just delete the numbers:

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

or even

 echo hgdfjg678gfdg kjg45nn | tr -d -c 0-9 
+12
source

You can use grep with the -o option to do this:

 $ echo hgdfjg678gfdg kjg45nn | grep -E -o "[0-9]+" 678 45 
+6
source

Or use tr :

 $ echo hgdfjg678gfdg kjg45nn | tr -d [az] 678 45 
+3
source

.* in sed is greedy. And there is no non-greedy AFAIK option.
(You should use [^0-9]* in this case for a non-greedy match, but this only works once, so you only get 678 without 45 )

If you should use only sed , getting the result will not be easy.
I recommend using gnus grep

 $ echo hgdfjg678gfdg kjg45nn | grep -oP '\d+' 678 45 

If you really want to stick with sed , this will be one of many possible answers.

 $ echo hgdfjg678gfdg kjg45nn | \ sed -e 's/\([0-9^]\)\([^0-9]\)/\1\n\2/g' | \ sed -n 's/[^0-9]*\([0-9]\+\).*/\1/p' 678 45 
+1
source

All Articles