开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜