Grep 正则表达式搜索教程
Grep(Global Regular Expression Print)是 Linux 中使用频率最高的文本搜索工具。它能够根据正则表达式从文件或输入流中快速筛选出匹配的行。在搬瓦工 VPS 日常运维中,Grep 用于日志排查、配置检索、安全审计等各种场景。本教程将系统讲解 Grep 的各种用法和正则表达式语法。
一、Grep 基本用法
# 在文件中搜索字符串
grep "error" /var/log/syslog
# 忽略大小写
grep -i "error" /var/log/syslog
# 显示行号
grep -n "error" /var/log/syslog
# 显示匹配行的上下文
grep -C 3 "error" /var/log/syslog # 前后各 3 行
grep -B 5 "error" /var/log/syslog # 前 5 行
grep -A 5 "error" /var/log/syslog # 后 5 行
# 递归搜索目录
grep -r "password" /etc/
grep -rn "listen" /etc/nginx/
# 只显示文件名
grep -rl "TODO" /var/www/
# 统计匹配行数
grep -c "404" access.log
# 反向匹配(不包含的行)
grep -v "^#" /etc/nginx/nginx.conf | grep -v "^$"
二、基础正则表达式(BRE)
# 行首匹配
grep "^root" /etc/passwd
# 行尾匹配
grep "bash$" /etc/passwd
# 任意单个字符
grep "h.t" file.txt # 匹配 hat, hot, hit 等
# 字符类
grep "[aeiou]" file.txt # 匹配任意元音字母
grep "[0-9]" file.txt # 匹配数字
grep "[^0-9]" file.txt # 匹配非数字字符
grep "[A-Za-z]" file.txt # 匹配任意字母
# 重复匹配
grep "go*d" file.txt # o 出现 0 次或多次
grep "go\+d" file.txt # o 出现 1 次或多次
grep "go\?d" file.txt # o 出现 0 次或 1 次
grep "go\{2,4\}d" file.txt # o 出现 2 到 4 次
# 转义特殊字符
grep "192\.168\.1\.1" config.txt
三、扩展正则表达式(ERE)
使用 grep -E(或 egrep)可以使用扩展正则,语法更简洁:
# 交替匹配(OR)
grep -E "error|warning|critical" /var/log/syslog
# 分组
grep -E "(http|https)://[^ ]+" access.log
# 量词不需要转义
grep -E "go{2,4}d" file.txt
grep -E "go+d" file.txt
grep -E "go?d" file.txt
# 匹配 IP 地址
grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log
# 匹配邮箱地址
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt
# 匹配日期格式
grep -E "[0-9]{4}-[0-9]{2}-[0-9]{2}" data.txt
四、Perl 正则表达式(PCRE)
使用 grep -P 可以启用 Perl 兼容正则,功能最为强大:
# 非贪婪匹配
grep -P '".*?"' data.json
# 前瞻与后顾
grep -P '(?<=port\s)\d+' config.txt # 匹配 port 后面的数字
grep -P '\d+(?=\sconnections)' log.txt # 匹配 connections 前面的数字
# 命名捕获组
grep -oP 'user=(?P\w+)' access.log
# \d \w \s 等简写字符类
grep -P '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' access.log
grep -P '\bword\b' file.txt # 单词边界匹配
# 只输出匹配部分
grep -oP '\d+\.\d+\.\d+\.\d+' access.log
五、实际运维应用
5.1 日志分析
# 查找今天的错误日志
grep "$(date '+%Y-%m-%d')" /var/log/syslog | grep -i "error"
# 查找 SSH 暴力破解尝试
grep "Failed password" /var/log/auth.log | grep -oP '\d+\.\d+\.\d+\.\d+' | sort | uniq -c | sort -rn | head -20
# 查找 Nginx 5xx 错误
grep -E '" [5][0-9]{2} ' /var/log/nginx/access.log
# 实时监控日志中的错误
tail -f /var/log/syslog | grep --line-buffered -iE "error|fail|critical"
# 查找特定时间段的日志
grep -E "^\S+ \S+ 14:(3[0-9]|4[0-9]|5[0-9])" access.log
5.2 安全审计
# 查找可疑的 crontab 条目
grep -rn "wget\|curl\|bash -i\|/dev/tcp" /var/spool/cron/ /etc/cron*
# 查找 SUID 文件的配置
grep -rn "chmod.*+s\|chmod.*4[0-9][0-9][0-9]" /var/log/
# 查找 PHP 后门特征
grep -rlE "eval\(base64_decode|system\(\\\$_|passthru|shell_exec" /var/www/
# 查找空密码账户
grep -E "^[^:]+::" /etc/shadow
# 查找监听端口配置
grep -rn "listen\|bind" /etc/nginx/ /etc/apache2/ /etc/mysql/
5.3 配置文件检索
# 查看有效配置行(去除注释和空行)
grep -vE "^\s*(#|;|$)" /etc/nginx/nginx.conf
# 查找所有包含特定域名的配置
grep -rl "example.com" /etc/nginx/conf.d/
# 查找 PHP 配置中的内存限制
grep -rn "memory_limit\|upload_max\|post_max" /etc/php/
# 查找 MySQL 配置
grep -vE "^(#|$)" /etc/mysql/my.cnf
六、Grep 性能优化
# 使用 --include 限制搜索文件类型
grep -rn --include="*.conf" "server_name" /etc/
# 使用 --exclude-dir 排除目录
grep -rn --exclude-dir=".git" "TODO" /var/www/
# 使用固定字符串模式(比正则更快)
grep -F "exact string" large_file.txt
# 使用 LC_ALL=C 加速(不处理多字节字符)
LC_ALL=C grep "pattern" large_file.log
# 找到第一个匹配就停止
grep -m 1 "pattern" huge_file.txt
# 使用 zgrep 搜索压缩文件
zgrep "error" /var/log/syslog.*.gz
七、Grep 与其他命令组合
# 结合 ps 查找进程
ps aux | grep "[n]ginx"
# 结合 find 搜索
find /var/log -name "*.log" -exec grep -l "error" {} \;
# 结合 history 查找历史命令
history | grep "docker"
# 结合 netstat 查找端口
netstat -tlnp | grep ":80\|:443"
# 统计代码行数(排除空行和注释)
grep -cvE "^\s*(#|//|$)" *.py | awk -F: '{sum+=$2} END{print sum}'
总结
Grep 是每个 Linux 管理员必须掌握的工具,配合正则表达式可以实现强大的文本搜索与过滤。在搬瓦工 VPS 运维中,Grep 常用于日志排查、安全审计和配置管理。建议搭配 AWK 与 Sed 教程 和 Find 与 Xargs 教程 一起学习,全面提升文本处理能力。选购搬瓦工 VPS 可参考全部方案,使用优惠码 NODESEEK2026 可享受 6.77% 循环折扣。