grep

grep

grep = 找行,awk = 切列,sed = 改内容

​ grep [选项] '搜索模式' [文件名]

选项 含义 示例
-i 忽略大小写 grep -i "error" log.txt
-v 反向匹配(不包含) grep -v "debug" log.txt
-n 显示行号 grep -n "warning" log.txt
-c 只统计匹配行数 grep -c "fail" log.txt
-l 只显示包含匹配的文件名 grep -l "TODO" *.py
-L 只显示不包含匹配的文件名 grep -L "完成" *.txt
-r / -R 递归搜索目录 grep -r "main" ./src/
-w 匹配整个单词 grep -w "to" text.txt(不匹配"today")
-x 匹配整行 grep -x "exact line" file.txt
-A n 显示匹配行及其后 n 行 grep -A 3 "error" log.txt
-B n 显示匹配行及其前 n 行 grep -B 2 "error" log.txt
-C n 显示匹配行及其前后各 n 行 grep -C 2 "error" log.txt
-e 指定多个模式 grep -e "error" -e "fail" log.txt
-f 从文件读取模式列表 grep -f patterns.txt log.txt
-o 只输出匹配的部分 grep -o "[0-9]\+" file.txt
--color 高亮显示匹配内容 grep --color "error" log.txt

实例

1.基础搜索
# 在文件中搜索包含 "hello" 的行
grep "hello" file.txt
# 忽略大小写搜索
grep -i "hello" file.txt
# 显示行号
grep -n "hello" file.txt

2.反向搜索与统计
# 找出不包含 "debug" 的行
grep -v "debug" log.txt
# 统计匹配行数
grep -c "error" log.txt

3.递归搜索目录
# 在 src 目录下所有 .py 文件中搜索 "main"
grep -r "main" ./src/ --include="*.py"

# 排除某些目录
grep -r "main" ./src/ --exclude-dir=__pycache__
4.显示上下文
# 显示错误行及其后 5 行
grep -A 5 "ERROR" log.txt

# 显示错误行及其前 3 行和后 3 行
grep -C 3 "ERROR" log.txt

5.正则匹配
# 匹配以数字开头的行
grep -E "^[0-9]" file.txt

6.多个模式
# 同时匹配 error 或 warn
grep -E "error|warn" log.txt
# 或使用 -e
grep -e "error" -e "warn" log.txt
# 从文件读取模式
grep -f patterns.txt log.txt
posted @ 2026-07-23 17:12  珉好好  阅读(3)  评论(0)    收藏  举报