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
相关推荐
tntxia1 天前
linux curl命令详解_curl详解
linux
扛枪的书生1 天前
Linux 网络管理器用法速查
linux
顺风尿一寸2 天前
Java Socket 内核之旅:从 SocketChannel.read() 到 tcp_recvmsg 与 epoll 的完整调用链路
linux
XIAOHEZIcode2 天前
Ubuntu 终端美化全栈指南:Bash 到 Kitty 踩坑实录
linux·ubuntu·命令行
唐青枫2 天前
别再只会用 cron:Linux systemd Timer 定时任务实战详解
linux
AlfredZhao4 天前
生产环境里,为什么不建议把普通端口直接暴露到公网?
linux·https·443·80
戴为沐5 天前
Linux内存扩容指南
linux
zylyehuo5 天前
Linux 彻底且安全地删除文件
linux
用户805533698036 天前
主线 U-Boot 上 RK3506:和闭源 rkbin 拔河的三个隐性契约
linux·嵌入式
用户034095297916 天前
linux fcitx 5 雾凇拼音 设置在中文输入法下仍然输入英文标点
linux