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

2 Answers 2


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.

  • 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.
    – quin16
    Sep 5, 2012 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, 2012 at 13:32

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

grep -E '^(\w+\b.){3}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .