在 grep 中用竖线(|)匹配多个关键字需启用扩展正则表达式(ere),最直接方式是加 -e 选项,如 grep -e 'apple|banana|cherry' file.txt;括号在 ere 中无需转义,可精确控制“或”范围;egrep 等价于 grep -e 但已过时;不加 -e 时 | 视为普通字符。

在 grep 中使用竖线(|)匹配多个关键字,本质是启用**扩展正则表达式(ERE)**,因为基础正则表达式(BRE)默认不支持 | 作为“或”操作符。
用 -E 参数启用扩展正则
最直接的方式是加 -E 选项,让 grep 解析扩展语法:
-
grep -E 'apple|banana|cherry' file.txt—— 匹配含 apple、banana 或 cherry 的任意一行 -
grep -E 'error|warning|critical' /var/log/syslog—— 同时抓取三类日志关键词
注意括号和转义的使用场景
如果需要对“或”的范围做精确控制(比如只让某几个词构成一个可选组),要用小括号 ();括号在 ERE 中无需反斜杠转义:
-
grep -E 'file (not found|permission denied)' error.log—— 匹配 “file not found” 或 “file permission denied” - 写成
file not found|permission denied就会变成匹配 “file not found” 或 “permission denied”,范围不对
替代方案:用 egrep(等价于 grep -E)
egrep 是传统命令别名,功能与 grep -E 完全一致,可直接使用:
egrep 'login|logout|failed' auth.log- 现代系统中推荐优先用
grep -E,因egrep已被标记为过时
避免常见错误
不用 -E 时,| 会被当作普通字符处理,无法实现“或”逻辑:
-
grep 'apple|banana' file实际匹配的是字面量 “apple|banana” 这个字符串,不是两个词任一 - 若坚持用 BRE,只能改用多次
grep管道或-e多次指定:grep -e apple -e banana file











