xtruder99
xtruder99

Reputation: 61

regexp to find all lines without a number pattern exept a specific number

I have some experience in regexp and grep command but couldn't find a way to do the following.

Lets immagine I have following text file:

abc 123 cdf
aze ert
vfg 12 gj
zrr 345 rty
top flg 567
aze 345 odi

I need to get all lines containing '345' and lines without other number matching the patern [0-9]{3} so it would return:

aze ert
vfg 12 gj
zrr 345 rty
aze 345 odi

Regards,
X

Upvotes: 3

Views: 103

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below.

grep -P '\b345\b|^(?!.*\b\d{3}\b)' file

\b345\b matches the line which contains the number 345 at very first.

(?!.*\b\d{3}\b) negative lookahead asserts that the line we are going to match won't contain a three digit number. If yes then it would match the start of that particular line. -P alone will print all the lines which has a match.

Upvotes: 1

xtruder99
xtruder99

Reputation: 61

Great thank you all !! never heard before about negative lookahead.

So, to explain further and give more simple regexp:

grep -P '345|^(?!.*[0-9]{3})' file

-P is to use perl style regexp (supporting the lookahead) ?! is the negative lookahead expression

Thanks.

Upvotes: 0

vks
vks

Reputation: 67968

^.*?345.*$|^(?!(?:.*\d){3,}).*$

Try this with grep -P.See demo.

https://regex101.com/r/iS6jF6/4

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

You need a negative look ahead, which grep supports if you use the -P (perl) option:

grep -P "\b345\b|^(?!.*\b[0-9]{3}\b)"

See demo

Upvotes: 1

Related Questions