Linux egrep 命令使用详解

简介

egrep(扩展 GREP)命令是 grep 的一个变体,支持扩展正则表达式 。它在功能上等同于 grep -E

基础语法

shell 复制代码
egrep [OPTIONS] PATTERN [FILE...]

或

grep -E [OPTIONS] PATTERN [FILE...]

示例用法

在文件中查找包含"error"的所有行

shell 复制代码
egrep "error" logfile.txt

大小写不敏感搜索

shell 复制代码
egrep -i "error" logfile.txt

使用多种模式 (|)

查找包含"error"或"warning"的行

shell 复制代码
egrep "error|warning" logfile.txt

使用 ?(匹配零次或一次出现)

查找"colou*r"(匹配"color"或"colour")

shell 复制代码
egrep "colou?r" file.txt

使用 +(匹配出现一次或多次)

查找"ab"、"abb"、"abbb"等

shell 复制代码
egrep "ab+" file.txt

使用 *(匹配零次或多次出现)

查找"ab"、"abb"、"abbb"甚至"a"

shell 复制代码
egrep "ab*" file.txt

使用 {}(精确或范围重复)

查找后面跟着 2 到 4 个"b"的"a"

shell 复制代码
egrep "ab{2,4}" file.txt

匹配行的开头 (^) 和结尾 ($)

  • 查找以"Error"开头的行
shell 复制代码
egrep "^Error" logfile.txt
  • 查找以"done"结尾的行
shell 复制代码
egrep "done$" logfile.txt

匹配特定字符集

  • 查找带有"gray"或"grey"的行
shell 复制代码
egrep "gr[ae]y" file.txt
  • 查找包含任意数字的行
shell 复制代码
egrep "[0-9]" file.txt
  • 查找没有数字的行([] 内的 ^ 表示否定)
shell 复制代码
egrep "[^0-9]" file.txt

使用括号进行分组

查找"foo1"或"foo2"但不查找"foo3"

shell 复制代码
egrep "foo(1|2)" file.txt

在多个文件中搜索

在所有 .log 文件中查找"error"

shell 复制代码
egrep "error" *.log

统计匹配到的次数

shell 复制代码
egrep -c "error" logfile.txt

显示行号(-n)

shell 复制代码
egrep -n "error" logfile.txt
相关推荐
chlk1231 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑2 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件2 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
深紫色的三北六号2 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash2 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI3 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行3 天前
Linux和window共享文件夹
linux
木心月转码ing4 天前
WSL+Cpp开发环境配置
linux
崔小汤呀5 天前
最全的docker安装笔记,包含CentOS和Ubuntu
linux·后端
何中应5 天前
vi编辑器使用
linux·后端·操作系统