Use grep to check if a sentence has less than 10 words

159 views Asked by At

Using grep to verify a sentence with less than 10 words (must start with a double quote then an uppercase letter and end with a dot and another double quote)

So far this is my code:

echo -e "\"This is a sentence.\""| grep -E '"[[:upper:]][[:upper:][:lower:] ]{1,10}\."'

The problem is: it seems to count the letters rather than the words. I wonder if there is any way to limit the words to just 10.

Any of your opinion is highly regarded.

3

There are 3 answers

1
Marc B On

Why use grep?

$ echo "This is a sentence" | wc -w
4

wc - word count.

0
DRC On

considering you must use grep and have constraints on the structure of the sentence, try

grep -E '"([[:upper:]]\w+)(\s\w+){0,9}\."'

It matches at least one word, starting with an uppercase, and max 10 words, all the sentence ended by a dot and enclosed in quotes.

Output examples from a shell:

$ echo -e "\"This.\""| grep -E '"([[:upper:]]\w+)(\s\w+){0,9}\."'
"This."


$ echo -e "\"This is a sentence with exactly ten words you see.\""| grep -E '"([[:upper:]]\w+)(\s\w+){0,9}\."'
"This is a sentence with exactly ten words you see."



$ echo -e "\"This is a sentence with more than ten words you see.\""| grep -E '"([[:upper:]]\w+)(\s\w+){0,9}\."'
0
Avinash Raj On

The below grep will print the strings which has less than 10 words that is from 1 to 9.

$ echo -e "\"This is a sentence.\"" | grep -P '^"[A-Z]\w*(\s+\w+){0,8}\."$'
"This is a sentence."
$ echo -e "\"This is a sentence foo bar fgb bghj ngh.\"" | grep -P '^"[A-Z]\w*(\s+\w+){0,8}\."$'
"This is a sentence foo bar fgb bghj ngh."
$ echo -e "\"This is a sentence foo bar fgb bghj ngh nar.\"" | grep -P '^"[A-Z]\w*(\s+\w+){0,8}\."$'
$