Alex Rivera | Logout

How do you use grep to find terms that are n characters long?

Asked 2010-05-22T07:11:39.307
15

I'm using grep to filter the Mac OS X dictionary words file (by default located at /usr/share/dict/words).

I want to use grep to retrieve all words four characters long. How do I do this?

My best guess for how to do this was:

grep [:alpha:]{4} words

But that returns zero results.

Edit
Report

1 Answer

29

It should be:

grep -E '^[[:alpha:]]{4}$' words

We anchor it (since a 5-letter string also contains a 4-letter string), and POSIX character classes must be contained in a bracket expression ([]). Also, we quote for the shell. And it needs to be extended, so -E.

answered 2010-05-22T07:14:02.893

Your Answer