grep 常用搜索与过滤速查

常用命令

grep 'error' app.log
grep -i 'error' app.log
grep -n 'error' app.log
grep -r 'TODO' ./src
grep -R --include='*.go' 'panic' .
grep -v '^#' config.conf
grep -E 'error|warn|fatal' app.log
grep -F 'a.b[c]' file
grep -A3 -B2 'exception' app.log
grep -c 'error' app.log
grep -l 'pattern' *.txt
grep -L 'pattern' *.txt
zgrep 'error' app.log.gz

常用选项

选项 含义
-i 忽略大小写
-n 显示行号
-r / -R 递归
-v 取反
-c 计数
-l / -L 只列匹配/不匹配文件
-A/-B/-C 后/前/上下文
-E 扩展正则
-F 固定字符串
--include / --exclude 文件过滤
-w 整词匹配

场景速查

目的 写法
排除目录 grep -r --exclude-dir=.git --exclude-dir=node_modules pattern .
只搜代码 grep -rn --include='*.py' pattern .
统计出现次数 `grep -o pattern file
显示前后文 grep -C3 pattern file
二进制文件 grep -a pattern file
压缩日志 zgrep pattern file.gz

易错点

相关命令