linux 正则表达式_6

本文详细介绍grep命令结合正则表达式的使用技巧,包括字符匹配、位置匹配、次数匹配及扩展正则表达式等,帮助读者掌握高效文本过滤的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

grep正则表达式 正则表达式 :所谓正则表达式就是用特殊字符组成字符串代表一类具有相同特征的文本。

过滤文件内容 ---- grep

grep [option] “pattern” 文件名称:

pattern模式:有普通字符和正则表达式的元字符组成的条件

[root@localhost ~]# grep "root" /etc/passwd   过滤出passwd文件中带有"root"的字符串

正则表达式的元字符
1 匹配单个字符:
. 任意单个字符
>>>过滤出passwd文件中以r开始t结尾中间任意两个字符的行
[root@localhost ~]# grep "r..t" /etc/passwd

[abc] 或者
过滤出zhang文件中以r开始t结尾中间是小a或者大A的行
[test@localhost test]$ grep "r[aA]t" zhang

连续的字符范围 [a-z] [A-Z] [a-zA-Z] [0-9] [a-zA-Z0-9]

[test@localhost test]$ grep "r[aA]t" zhang
[test@localhost test]$ grep "r[a-zA-Z0-9]t" zhang 

^ 取反

[test@localhost test]$ grep "r[^0-9]t" zhang 

特殊的字符集:
[[:punct:]] 任意单个标点
[[:space:]] 任意单个空白字符

  [test@localhost test]$ grep "r[[:space:]]t" zhang 
  [test@localhost test]$ grep "r[[:punct:]]t" zhang 

2 匹配字符出现的位置

^String 以String开头

	[test@localhost test]$ grep "^root" /etc/passwd

	[test@localhost test]$ grep "^[brh]" /etc/passwd    >>>以r或b或h开头的行

	[test@localhost test]$ grep "^[^brh]" /etc/passwd   >>>不是以r或b或h开头的行

string$ 以sting结尾

	[test@localhost test]$ grep "bash$"  /etc/passwd
	[test@localhost test]$ grep  "nologin$"  /etc/passwd   |wc -l

^$ 空行

[test@localhost test]$ grep "^$" /etc/fstab | wc -l

[test@localhost test]$ ls -l /etc/  | grep "^d"      >>>列出/etc/所有的目录。

3)匹配字符出现的次数:

*  匹配前一个字符出现任意次  ab* 表示b出现的任意次
   
   [test@192 test]$ grep "ab*" zhang         >>> b出现的任意次数
  	   
   [test@192 test]$ grep ".*" zhang          >>> .*任意字符出现的位置
   
   [test@192 test]$ grep "b\+" zhang         >>> \ 转移符  表示b最少出现一次
   
   [test@192 test]$ grep "b\?" zhang         >>> 表示b出现0次或者1次 可有可无
       
   [test@192 test]$ grep "ab\{2\}" zhang     >>> 表示b出现两次。精确。
   
   [test@192 test]$ grep "ab\{2,5\}" zhang   >>> 表示b最少出现两次最多出现五次。
   

分组 :多个字符当成一个字符来处理:
   
   [test@192 test]$ grep  "\(ab\)\{2,\}" /usr/share/dict/words    >>> 表示ab至少出现两次以上。

grep [option] grep 命令常用的选项:

1)-i 忽略大小写

  [test@192 test]$ grep -i "^a" zhang       >>>过滤文件中以a开始的行不区分大小写。

2)-o

  [test@192 test]$ grep -o  "r..t" /etc/passwd  >>>仅显示符合正则表达式的内容,不在全部显示。

3)-v 反向过滤

  [test@192 test]$ grep  -v  "^#" /etc/fstab     >>>显示不符合条件的行
  [test@192 test]$ grep -v -e "^$" -e "^#" /etc/fstab 

4)-e 根据多个条件过滤文本

  [test@192 test]$ grep  -e "^$" -e "^#" /etc/fstab  

5)-E 支持扩展正则表达式:

  [test@192 test]$ grep  -E  "(ab){2,}" /usr/share/dict/words 

6)|
[test@192 test]$ grep -E "vmx|svm" /proc/cpuinfo 查看虚拟机支不支持虚拟化

7)-A -n 同时显示符合条件的后n行。

  [test@192 test]$ ifconfig eno16777736 | grep -A 2 "netmask"

7)-B -n 同时显示符合条件的后n行。

  [test@192 test]$ ifconfig eno16777736 | grep -B 2 "netmask"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值