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

First off, this is homework and unfortunately I have to use egrep (and not with -w or anything of the like).

I need my grep to return lines that have exactly 5 or 6 upper case letters.

Doing egrep [A-Z]{5,6} .filename returns 5 and 6 letter words, but also unfortunately also more letter words than that.

So I for example in this list:

roger ROBERT gulliver
MELISSA tenant

I need it to return only ROBERT and THOMAS.

share|improve this question
+1 all around, I wish I had more opportunity to use regexp's in my work life! – DCookie Mar 24 '11 at 21:20
up vote 3 down vote accepted
egrep "^[^A-Z]*[A-Z]{5,6}[^A-Z]*$" .filename
share|improve this answer
PERFECT Thank you sir. – roger34 Mar 24 '11 at 21:11
Update: you are explicitly talking about no more than 7 uppercase letters. I'm not sure what you want with lowercase. My regexp does allow xROBERTx, while cYrus' regexp refuses it. – Geeklab Mar 24 '11 at 21:15

Try with:

egrep '^[A-Z]{5,6}$'

where ^ and $ match beginning and ending of the line, respectively.

share|improve this answer
Forgot to mention that the words in the list were not at the start or end of the lines, my bad. Geeklab below had the right formula for the alternate version. Thanks for the help. – roger34 Mar 24 '11 at 21:13

Yet another version

a) limited to 5 or 6 Upper Cases in the word;

b) word can have unlimited lower case, plus the '-' and the apostrophe: '

c) uses the \b word edge character (zero-width);

This finds more than your list, (which you would want), and follows all limitations you state. This may result in more than you bargained for, since it also permits any number of lower-case letters between the upper-case letters:


Will find: awesome JET-LI


But not: old MacDONALD

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.