Just like the title says. How do I identify (and goto) a line based on its word count? For example, what if I want to go to the next line containing more than 5 words?


Use regular expressions to match lines containing at least four words (sequences of at least one non-blank character) followed by spaces (sequences of at least one blank character), plus a fifth non-blank character indicating the fifth word.

You can use \S and \s to match non-blanks and blanks. You can use \{4} to match 4 of a pattern. And \+ to match the repeats of non-blanks and blanks.

I recommend using "very magic" regular expressions, which will save you from having to type (even more) backslashes!

To match exactly 5 words on a line:


Matches optional whitespace, followed by 4 repetitions of a word with spaces after it, followed by a fifth word, optional whitespace and the end of the line.

To match at least 5 words on a line:


You can make use of a substring match in that case. As long as you're seeing the 4 sets of spaces in between words, you know there are at least 5 words.

If you want to use a different definition of a word (for example, sequences of \w or \k characters) then use the corresponding opposite (\W or \K) for the separators in between the words.

|improve this answer|||||
  • 1
    That answers my question. Thanks for your help! – JMW Feb 29 at 0:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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