Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have file like this :

 other lines . . .    
 blah blah blah (:34)

I wish to find the occurrence of numbers in the above file. I came up with :

grep [0-9] filename

But that is printing the whole:

blah blah blah (:34)

Rather I want only 34. Is there any way to do so?

share|improve this question
    
In the future, also check out the man page for grep (or any other program). The man page details the options required for many common uses of the program. e.g. man grep –  hnasarat Sep 5 '12 at 4:33
    
You can try this >grep -o '[0-9][0-9]*' testfile –  user159512 May 17 '13 at 10:18

2 Answers 2

up vote 9 down vote accepted

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

share|improve this answer
    
Nice. Also, to match more than 4 or arbitrary number of digits, use grep -Eo '[0-9]{1,}' testfile –  FractalSpace Aug 13 at 19:32

grep -o will print only the matching part of the line. Otherwise grep will print any lines with the pattern.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.