Skip to content

grep命令常见用法

1421字约5分钟

linux

2025-03-28

一、基础用法

1.语法

grep [OPTIONS] PATTERN [FILE...]

2.常用操作操作

搜索文件中内容

grep "error" test.log        # 在 test.log 中查找包含 "error" 的行

多文件搜索

grep "404" access.log error.log test.log  # 同时在三个文件中搜索

忽略大小写

grep -i "warning" test.log    # 匹配 "WARNING"、"warning" 等

显示匹配行号

grep -n "TODO" xxxx.java      # 输出格式:文件名:行号:内容

统计匹配次数

grep -c "GET" test.log    # 输出匹配的行数(非总匹配次数!)

二、递归搜索与文件过滤

1.递归搜索目录

grep -r "config" /etc/        # 搜索 /etc/ 下所有文件中的 "config"

2.精准控制搜索范围

仅搜索特定文件类型

grep -r --include="*.conf" "port" /etc/  # 只搜索 .conf 文件

排除特定文件/目录

grep -r --exclude="*.tmp" "debug" .      # 排除 .tmp 文件
grep -r --exclude-dir=".git" "TODO" .    # 排除 .git 目录

多条件过滤

grep -r --include="*.{js,css}" --exclude="*.min.*" "color" ./src  # 搜索 js/css 文件,排除 min 文件

三、输出控制与上下文

1.高亮显示匹配内容

grep --color=auto "error" test.log   # 自动高亮(通常可设为默认别名)

2.显示上下文行

显示匹配行前后内容

grep -A 3 "panic" test.log      # 显示匹配行及其后3行(After)
grep -B 2 "timeout" test.log # 显示匹配行及其前2行(Before)
grep -C 2 "test" test.log   # 显示匹配行及其前后各2行(Context)

分页查看(保留颜色)

grep --color=always "error" test.log | less -R  # 按页查看,支持颜色

3.仅输出匹配内容

grep -o "user_[0-9]+" logs.txt  # 只输出 "user_123" 这样的匹配项,每项一行

4.静默模式(脚本中使用)

if grep -q "success" status.txt; then
  echo "任务完成!"
fi

四、正则表达式高级技巧

1.基础正则表达式(BRE)

锚定行首/行尾

grep "^start" test.txt       # 匹配以 "start" 开头的行
grep "end$" test.txt         # 匹配以 "end" 结尾的行

匹配任意字符

grep "f.x" test.txt         # 匹配 "fox"、"fix"、"f3x" 等

字符集合

grep "[aeiou]" test.txt    # 匹配包含元音字母的行
grep "[^0-9]" test.txt      # 匹配包含非数字字符的行

2.扩展正则表达式(ERE)

grep -E "(error|warn)" test.log    # 匹配 "error" 或 "warn"
grep -E "[0-9]{3}-[0-9]{4}" test.txt  # 匹配电话号码(如 123-4567)

3.Perl兼容正则(PCRE,需 GNU grep)

grep -P "\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b" test.log  # 匹配IP地址
grep -P "\d+(?= ms)" test.log       # 正向预查(匹配 "123 ms" 中的 123)

4.特殊符号转义

grep "https://lixxing.com" test.txt    # 转义特殊字符 / 和 .
grep -F ".*$special[char]" test.txt      # -F 禁用正则,按字面搜索

五、高级技巧

1.反向匹配(排除模式)

grep -v "200" test.log        # 排除状态码为200的行
grep -v "^#" /usr/local/nginx/conf/nginx.conf  # 排除注释行(以#开头)

2.多模式组合搜索

grep -e "error" -e "critical" test.log  # 匹配包含 error 或 critical 的行
grep -E "error|(warning.*failed)" log  # 组合复杂逻辑

3.处理二进制文件

grep -a "text_in_binary" binary.data   # 强制以文本方式处理二进制文件
strings binary.exe | grep "version"    # 结合 strings 提取二进制文件中的文本

4.提取结构化数据

提取邮箱地址

grep -Eo "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}\b" test.txt

提取URL

grep -Eo "https?://[a-zA-Z0-9./?=_-]+" test.html

5.进程过滤技巧

ps aux | grep "[n]ginx"          # 查找 nginx 进程(避免显示 grep 自身)
pgrep -f "java.*spring" | xargs ps -fp  # 结合 pgrep 精确过滤进程

六、性能优化与陷阱

1.加速大文件搜索

grep -m 100 "error" large.log    # 找到100个匹配后停止
LC_ALL=C grep "pattern" bigfile  # 禁用本地化,加速ASCII搜索

2.避免内存溢出

grep "pattern" test.log | head -n 50  # 仅显示前50条结果(不加载整个文件)

3.排除干扰

grep -s "error" *.log            # 忽略文件不存在或无权限的报错
grep -d skip "config" /dev/*     # 跳过设备文件等特殊文件

4.结合 find 高效搜索

find /var/log -name "*.log" -exec grep -H "error" {} +  # 快速搜索所有 .log 文件
find . -type f -mtime -7 | xargs grep "debug"          # 搜索最近7天修改过的文件

七、实用技巧

1.多行匹配(需 GNU grep)

grep -Pzo "start(\n.*)+end" test.txt  # 匹配从 start 到 end 的多行内容

2.仅匹配完整单词

grep -w "word" test.txt        # 匹配 "word" 而不是 "password"

3.统计所有匹配项总数

grep -o "error" test.log | wc -l  # 统计 "error" 出现的总次数

4.压缩文件搜索

zgrep "error" /var/log/test.*.gz  # 直接搜索 gzip 压缩文件

八、实践

1.日志分析

# 查找过去1小时内包含 "timeout" 的错误,显示上下文
grep -C 2 "timeout" /var/log/app/$(date +"%Y-%m-%d").log

2.代码审查

# 搜索所有 Java 文件中的密码硬编码(排除测试目录)
grep -rn --include="*.java" --exclude-dir="tests" "PASSWORD =" ./src

3.网络诊断

# 提取访问量最高的10个IP地址
grep -oP "\d+.\d+.\d+.\d+" test.log | sort | uniq -c | sort -nr | head

4.JSON解析

示例JSON:

[
  {
    "id": 1,
    "name": "test1",
    "email": "test@lixxing.com"
  },
  {
    "id": 2,
    "name": "test2",
    "email": "test@lixxing.com"
  }
]

提取 email 字段

# 提取JSON中的某个key值
grep -o '"email": "[^"]*' test.json | grep -o '[^"]*$'

九、组合使用

1.与 awk 组合

grep "500" test.log | awk '{print $1, $7}'  # 提取IP和请求路径

2.与 sed 组合

grep "user_id=" test.log | sed 's/.*user_id=([0-9]+).*/\1/'  # 提取用户ID

3.批量替换前检查

grep -rl "old_string" . | xargs sed -i 's/old_string/new_string/g'  # 先检查再替换

常用选项速查表

选项作用
-i忽略大小写
-v反向匹配
-r递归搜索
-l仅显示文件名
-n显示行号
-C显示上下文行
-PPerl正则(GNU特有)
-E扩展正则
-F固定字符串匹配

Powered by Vuepress and Cloudflare Pages