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
相关推荐
ARTHUR-SYS7 分钟前
基于Kali linux 安装pyenv及简单使用方法及碰到的问题
linux·运维·chrome
南山鹤16616 分钟前
中型规模生产架构部署详细步骤
linux
IvanCodes20 分钟前
十六、Linux网络基础理论 - OSI模型、TCP/IP协议与IP地址详解
linux·网络·tcp/ip
shylyly_22 分钟前
Linux-> TCP 编程2
linux·服务器·网络·tcp/ip·松耦合·command程序
upgrador1 小时前
操作系统命令:Linux与Shell(Operating System & Command Line, OS/CLI)目录导航、文件操作与日志查看命令实践
linux·ubuntu·centos
夜月yeyue1 小时前
多级流水线与指令预测
linux·网络·stm32·单片机·嵌入式硬件
IvanCodes2 小时前
十五、深入理解 SELinux
linux·运维·服务器
云博客-资源宝2 小时前
【防火墙源码】WordPress防火墙插件1.0测试版
linux·服务器·数据库
qq_479875432 小时前
systemd-resolved.service实验实战2
linux·服务器·网络
CS Beginner4 小时前
【Linux】安装配置mysql中出现的问题2
linux·mysql·adb