How do I fetch only numbers in grep?

You can use grep -E to access the extended regular expression syntax( Same as egrep)

I have created a testfile with below contents:

>cat testfile
this is some text
with some random lines

again some text
ok now going for numbers (:32)
ok now going for numbers (:12)
ok now going for numbers (:132)
ok now going for numbers (:1324)

Now to grep the numbers alone from the text you can use

>grep -Eo '[0-9]{1,4}' testfile
32
12
132
1324

will be output.

Here "-o" is used to only output the matching segment of the line, rather than the full contents of the line.

The squiggly brackets (e.g. { and }) indicate the number of instances of the match. {1,4} requires that the previous character or character class must occur at least once, but no more than four times.

Hope this helps


You can use RE bracket expression [:digit:] specified by section 9.3.5 of POSIX standard , in combination with -o flag to print only matching "words"

$ grep -o '[[:digit:]]*' <<< $'No number in this line\nbut 123 here'                                                     
123