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"