Shell 编程/正则表达式
外观
< 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 中搜索它。