Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match lines with pattern n times in the same line

Tags:

regex

grep

vim

sed

awk

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

like image 631
lodge Avatar asked Dec 16 '22 14:12

lodge


1 Answers

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

like image 190
manojlds Avatar answered Jan 10 '23 02:01

manojlds