2012-10-25 30 views
0

我們可以搜索一個像「\ w \ w \ w \ d」這樣的模式,它表示三個字母后跟grep中的數字嗎?它不工作。有什麼辦法可以在linux終端上做同樣的事情嗎?正則表達式 - Linux

例如,我想匹配 'ABC9' 或 'NMJ6' 等

+0

給我們,你想一個字符串的一個實例比賽。 – David

回答

2
grep -P '\w\w\w\d' 

添加--color讓它真正脫穎而出。 例如:

echo 'blahblahABC9blahblah' | grep --color -P '\w\w\w\d' 
+0

謝謝大家的幫助。 – gthm

2

的grep -P 「\ W \ W \ W \ d」

-P, --perl-regexp 
Interpret PATTERN as a Perl regular expression. 
3

例如:

 
echo ABC9 | grep -E '[[:alpha:]]{3}[[:digit:]]' - 

這使得使用字符類由man grep定義:

Finally, certain named classes of characters are predefined 
    within bracket expressions, as follows. Their names are self 
    explanatory, and they are [:alnum:], [:alpha:], [:cntrl:], 
    [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], 
    [:upper:], and [:xdigit:]. For example, [[:alnum:]] means 
    [0-9A-Za-z], except the latter form depends upon the C locale and 
    the ASCII character encoding, whereas the former is independent 
    of locale and character set. (Note that the brackets in these 
    class names are part of the symbolic names, and must be included 
    in addition to the brackets delimiting the bracket expression.) 
    Most meta-characters lose their special meaning inside bracket 
    expressions. To include a literal ] place it first in the list. 
    Similarly, to include a literal^place it anywhere but first. 
    Finally, to include a literal - place it last.