• Uncategorized

About regex : Finding-a-certain-set-of-numbers-in-egrep

Question Detail

I am currently stuck on trying to solve this issue I am having. I am trying to use egrep to find either 5 digit consecutive numbers or 9 digit consecutive numbers.

Right now I am getting only the 5 digit number that appears on one line and nothing else after that. I currently have…

egrep '^[[:digit:]]{5} | [[:digit:]]{9}$' file.txt

For example if my file.txt had

123456789 24
12345 642
94363

What will be found is

12345 642

How can I make it so that it will check every line and see the other 5 and 9 digit numbers?

Edit:Using parentheses around the expression finds…

123456789 4

12345 642

Question Answer

egrep '^[[:digit:]]{5} | [[:digit:]]{9}$' file.txt

remove space after ^[[:digit:]]{5}, the 3th line no space after 5 digit, so can’t match.

remove space before [[:digit:]]{9}, the first line no space before 123456789, so can’t match it.

Use () around the expression:

$ egrep "(^| )([[:digit:]]{5}|[[:digit:]]{9})( |$)" file
123456789 24
12345 642
94363

Add ^ and $ if needed.

Edit: If you add -o to the egrep you see what you get:

$ egrep -o "(^| )([[:digit:]]{5}|[[:digit:]]{9})( |$)" file
123456789 
12345 
94363

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.