shell中正则表达式

在 Linux 中, grep , sed, awk 等文本处理工具都支持通过正则表达式进行模式匹配

复制代码
示例1:匹配passwd中所有包含 atguigu 的行。

[atguigu@hadoop101 shells]$ cat /etc/passwd | grep atguigu

1.常用特殊字符 ^ $ . * \

**^ :**匹配一行的开头

**$ :**匹配一行的结束

**. :**匹配一个任意的字符

*** :**不单独使用,他和上一个字符连用,表示匹配上一个字符 0 次或多次

** :**表示匹配某个范围内的一个字符

**\ :**表示转义,并不会单独使用。由于所有特殊字符都有其特定匹配模式,当我们想匹配
某一特殊字符本身时(例如,我想找出所有包含 '$' 的行),就会碰到困难。此时我们就要
将转义字符和特殊字符连用,来表示特殊字符本身

bash 复制代码
以下都是在passwd中匹配

会匹配出所有以 a 开头的行
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep ^a

匹配出所有以 t 结尾的行
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep t$

会匹配包含 rabt,rbbt,rxdt,root 等的所有行,两个点代表两个字符
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep r..t

会匹配 rt, rot, root, rooot, roooot 等所有行
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep ro*t

匹配 rt,rat, rbt, rabt, rbact,rabccbaaacbt 等等所有行
[6,8]------匹配 6 或者 8
[0-9]------匹配一个 0-9 的数字
[0-9]*------匹配任意长度的数字字符串
[a-z]------匹配一个 a-z 之间的字符
[a-z]* ------匹配任意长度的字母字符串
[a-c, e-f]-匹配 a-c 或者 e-f 之间的任意字符
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep r[a,b,c]*t

就会匹配所有包含 /$b 的行。注意需要使用单引号将表达式引起来
[atguigu@hadoop101 shells]$ cat /etc/passwd | grep '/\$b' 
相关推荐
阿里云大数据AI技术15 小时前
阿里云 EMR AI 助手正式发布:从问答工具到全栈智能运维助手
运维·人工智能
orion571 天前
Missing Semester Class1:course overview and introduction of shell
linux
SkyWalking中文站2 天前
认识 Horizon UI · 6/17:Trace 探索器
运维·监控·自动化运维
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
火车叼位2 天前
写给初级开发者:SSL、SSH、HTTPS 与证书体系全解析
运维
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698032 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
小猿姐2 天前
唯品会大规模数据库云原生实践:基于 KubeBlocks 管理数千实例的统一运维之路
运维·elasticsearch·云原生
七歌杜金房2 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
SkyWalking中文站3 天前
认识 Horizon UI · 5/17:3D 基础设施地图
运维·监控·自动化运维