正则表达式普通常用的元字符
. 匹配除了换行符以外的任意单个字符
* 前导字符出现0次或连续多次
.* 任意长度字符 ab.*
^ 行首(以...开头) ^root
$ 行尾(以...结尾) bash$
^$ 空行
[] 匹配括号里任意单个字符或一组单个字符 [abc]
[^] 匹配不包含括号里任一单个字符或一组单个字符 [^abc]
^[] 匹配以括号里任意单个字符或一组单个字符开头 ^[abc]
\^[\^] 匹配不以括号里任意单个字符或一组单个字符开头 \^[^abc]
< 词首定位符
> 词尾定位符
[root@linux /]# grep "^root" /etc/passwd #查询以root开头的行
root:x:0:0:root:/root:/bin/bash
[root@linux /]# grep "t$" /etc/passwd # 匹配以t结尾的行
halt:x:7:0:halt:/sbin:/sbin/halt
[root@linux /]# grep 'ro*t' /etc/passwd #匹配ro t中间的多次字符
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@linux /]# grep 'r..t' /etc/passwd ## 2点,匹配两个字符的内容
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[root@linux /]# grep '[Rr]oot' /etc/passwd # 匹配R或者r的一个字符
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@linux /]# grep '[a-z]oot' /etc/passwd #匹配小写a到z的一个字符
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@linux /]# grep [^root] /etc/passwd #匹配非root的字符
adm:x:3:4:adm:/var/adm:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
[root@linux /]# cat 0.txt
<root>
/root/
[root@linux /]# grep "<root" 0.txt
<root>
[root@linux /]# grep "root>" 0.txt
<root>
[root@linux /]# grep "a\{1\}" 0.txt #a出现2次的显示
aa123456
213456a
[root@linux /]# grep "a\{2,\}" 0.txt #a出现2次以上的显示
aa123456
[root@linux /]# grep "a\{2,6\}" 0.txt #a出现2到6次之间的显示
aa123456
扩展类正则常用元字符
+ 匹配一个或多个字母
? 表示0-1个字符
() 找出组字符串
(ab|de)+ # 匹配一连串的(最少一个)abc或def,abc和def将匹配
[[:alpha:]] 代表所有字母不论大小写
[[:lower:]] 表示小写字母
[[:upper:]] 表示大写字母
[[:digit:]] 表示数字字符
[:digit:] 表示数字字符加小写字母
[root@linux /]# egrep "a+" 0.txt
aa123456
213456a
[root@linux /]# cat 0.txt
aa123456
213456a
45966bb
god
gd
[root@linux /]# egrep "go?d" 0.txt 查找god和gd这两个字符串
god
gd
[root@linux /]# cat 0.txt
hello
hlllo
heeee
[root@linux /]# egrep 'h(ell|lll)o' 0.txt #查找hello和hlllo这两个字符串
hello
hlllo
[root@linux /]# cat 0.txt
abdd123
default
124585
[root@linux /]# egrep "(ab|de)+" 0.txt
abdd123
default
[root@linux /]# cat 0.txt
abdd123
default
Adaca
[root@linux /]# egrep "[[:alpha:]]" 0.txt #匹配所有的大小写字符
abdd123
default
Adaca
[root@linux /]# cat 0.txt
abdd123
default
AABB
[root@linux /]# egrep "[[:lower:]]" 0.txt #匹配小写字符
abdd123
default
[root@linux /]# cat 0.txt
abdd123
default
AABB
[root@linux /]# egrep "[[:upper:]]" 0.txt #匹配大写字符
AABB
[root@linux /]# cat 0.txt
abdd123
default
AABB
[root@linux /]# egrep "[[:digit:]]" 0.txt #匹配数字
abdd123
[root@linux /]# cat 0.txt
abdd123
default
AABB
[root@linux /]# egrep "[[:digit:][:lower:]]" 0.txt #匹配数字和小写字符
abdd123
default