Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
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
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


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.