Reputation: 61
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
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
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
Reputation: 67968
^.*?345.*$|^(?!(?:.*\d){3,}).*$
Try this with grep -P
.See demo.
https://regex101.com/r/iS6jF6/4
Upvotes: 0