Shell 程式設計/正則表示式
外觀
正則表示式通常用於透過像 find 和 grep 這樣的外部程式來操作字串。
^ Anchor to beginning of line $ Anchor to end of line . Any single character [ ] Encloses pattern matching characters
[:alnum:] Alphanumeric characters [:alpha:] Letters [:ascii:] ASCII characters [:blank:] Space or tab [:cntrl:] ASCII control characters [:digit:] Digits [:graph:] Noncontrol, nonspace characters [:lower:] Lowercase letters [:print:] Printable characters [:punct:] Punctuation characters [:space:] Whitespace characters, including vertical tab [:upper:] Uppercase letters [:xdigit:] Hexadecimal digits
可以使用 -E 模式在 grep 中使用以下以 '\' 開頭的字元。
? Match is optional but may be matched at most once
"*" Must be matched zero or more times (without "")
+ Must be matched one or more times
{n} Must be matched n times
{n, } Must be matched n or more times
{n,m} Must be matched between n and m times
- 在檔案 example_text_file 中查詢以 'e' 結尾的文字
grep e$ example_text_file
- 查詢
Crazy Monkey Crazy Donkey Cranky Money
在 another_text_file 中
grep -E Cra..\*[[:space:]][[:print:]]o... another_text_file
上面的命令告訴 grep 使用擴充套件模式,查詢 "Cra",後面跟著任意數量的字串,後面跟著空格,後面跟著可列印字元,後面跟著 "o",後面跟著三個字元,並在 another_text_file 中搜索它。