Take the 2-minute tour ×

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

share|improve this question
add comment

2 Answers

up vote 3 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
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
add comment

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

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

Your Answer


