Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there a way to find all lines with grep, that contains at least x words?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Well, assuming words are separated by spaces, to find lines with >= 5 words, do this:

$ grep -P '\w+\s+\w+\s+\w+\s+\w+\s+\w+'

Grep is not the best tool for the job though, try gawk:

$ gawk 'NF>4'

Gawk's NF variable holds the number of fields, by default fields are defined by spaces, so in a line of text each field is a word. The command above will print all lines containing more than 4 words.

share|improve this answer
2  
But words can also be separated by comma. And at the end of the sentence there is dot. I try this: grep -E "(\w+[ ,.]+){25,}" and it seems to work allright. –  quin61 Sep 5 '12 at 11:01
    
My gawk command counts fields @quin61, three spaces means four fields. The dot is irrelevant and, in normal text, there is a space after the comma. –  terdon Sep 5 '12 at 13:32

Replace the number "3" if you want lines >= to a different value.

grep -E '^(\w+\b.){3}'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.