I have a file and I need to filter lines that have (or don't have) N occurrences of a pattern.
I.e., if my pattern is the letter o
and I what to match lines where the letter o
occurs exactly 4 times, the expression should match the first of the following example lines but not the others:
foo foo
foo
foo foo foo
I thouth I could do it with a regex in vim, or sed, awk, or any other tool. I've googled and haven't found anyone that has done a similar thing. Probably will have do a script or something similar to parse each line. Does anyone have done a similar thing?
Thanks
You can use a regex like below:
(?=(.*o){4})(?!(.*o){5,}).*
Regexr - http://regexr.com?2toro
This should work with any pattern you want. For instance, you want to find lines with exactly four foos in it, use:
(?=(.*foo){4})(?!(.*foo){5,}).*
Regexr - http://regexr.com?2tosa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With