Vipul Priyadarshi
Vipul Priyadarshi

Reputation: 101

Grep for line having only 2 or 3 digits

I'm trying to print line containing 2 or 3 numbers along with the rest of the line. I came with the code:

grep -P '[[:digit:]]{2,3}' address

But this even prints the line having 4 digits. I don know why is this happening.

Output: enter image description here Neither this code works;

grep -E '[0-9]{2,3}' address

enter image description here

Here is the file containing address text:

12 main st

123 main street

1234 main street

I have already specified to print 2 or 3 values with {2,3} still the filter doesn't work and more than 3 digits line is being printed. Can anyone assist me on this? Thank you so much.

Upvotes: 1

Views: 7744

Answers (1)

NSegal
NSegal

Reputation: 56

You can use inverted grep (-v) to filter all lines with 4 digits (and above):

grep -vE '[0-9]{4}' address

EDIT:

I noticed you want only 2 or 3 digit along the line, so first command will get you also 1 digit.

Here's the fix, again using same method:

grep -E '[0-9]{2,3}' txt.txt | grep -vE '[0-9]{4}'

Upvotes: 2

Related Questions