Sunday, May 5, 2024
142
rated 0 times [  142] [ 0]  / answers: 1 / hits: 375800  / 3 Years ago, mon, september 27, 2021, 6:11:23

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?


More From » command-line

 Answers
3

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


[#35752] Tuesday, September 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
unsmmoth

Total Points: 72
Total Questions: 113
Total Answers: 95

Location: Thailand
Member since Tue, Oct 6, 2020
4 Years ago
;