How do you use grep to find terms that are n characters long?
I'm using grep to filter the Mac OS X dict开发者_StackOverflowionary 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.
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.
Trying to remember how much of regex language grep
supports... does
grep '^....$' words
work for you? Note that since you are searching a dictionary file, I'm not sure you need to restrict yourself to letters.
精彩评论