基本正则表达式元字符:BRE basi
字符匹配
.:匹配任意单个字符
[root@localhost dev]# grep r…t /etc/passwd
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@localhost dev]# grep s[abcd]i /etc/passwd
bin: x :1:1:bin:/bin:/sbin/nologin
daemon: x :2:2:daemon:/sbin:/sbin/nologin
adm: x :3:4:adm:/var/adm:/sbin/nologin
lp: x :4:7:lp:/var/spool/lpd:/sbin/nologin
sync: x :5:0:sync:/sbin:/bin/sync
shutdown: x :6:0:shutdown:/sbin:/sbin/shutdown
[^]:匹配指定范围外的任意单个字符
[root@localhost dev]# grep s[^1234]i /etc/passwd
bin: x :1:1:bin:/bin:/sbin/nologin
daemon: x :2:2:daemon:/sbin:/sbin/nologin
adm: x :3:4:adm:/var/adm:/sbin/nologin
lp: x :4:7:lp:/var/spool/lpd:/sbin/nologin
sync: x :5:0:sync:/sbin:/bin/sync
shutdown: x :6:0:shutdown:/sbin:/sbin/shutdown
[:digit:]:数字
[[:digit:]],[[:lower:]],[[:upper:]]:匹配任意字数/小写字母/大写字母
匹配次数
*:匹配前面字符任意次数
.*:匹配任意长度的任意字符
\?:匹配前面的字符0次或者一次
\ +:匹配一次或者多次
\ {m,n \ }:可以匹配至少m次,至多n次
位置锚定
^:行首锚定
$:行尾锚定
[root@localhost dev]# grep ^r…t /etc/passwd
root: x :0:0:root:/root:/bin/bash
[root@localhost dev]# grep bash$ /etc/passwd
root: x :0:0:root:/root:/bin/bash
^$:空行
^ [ [:space:] ]$:空行
\ < 、 \ b:词首锚定
[root@localhost dev]# grep “<root” /etc/passwd
root: x :0:0:root:/root:/bin/bash
operator: x :11:0:operator:/root:/sbin/nologin
[root@localhost dev]# grep “root>” /etc/passwd
root: x :0:0:root:/root:/bin/bash
operator: x :11:0:operator:/root:/sbin/nologin
练习:
1、显示/etc/passwd中不以/bin/bash结尾的行
[root@localhost dev]# grep [ ^/bin/bash $ ] /etc/passwd
[root@localhost dev]# grep -v /bin/bash $ /etc/passwd
2、找出/etc/passwd中两位数
[root@localhost dev]# grep -0 "\<[0-9]\{2\}\>" /etc/passwd
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
[root@localhost dev]# grep -o "\<[0-9]\{2\}\>" /etc/passwd
12
10
14
11
12
13
30
14
50
99
99
69
69
76
89
89
74
74
3、找出ifconfig命令中IP地址
[root@localhost dev]# ifconfig eth0 |grep inet |grep -v inet6 | cut -b 21-35
分组和引用
\ (\ ):
\ (xy\ )\ (zd\ )ab\1:把xy当做第一组,把zd当做第二组,取第一组
[root@localhost dev]# cat file
he loves his lover
he likes his lover
she loves her lover
she likes her liker
[root@localhost dev]# grep l…e.l…e file
he loves his lover
he likes his lover
she loves her lover
she likes her liker
[root@localhost dev]# grep "(l…e).\1" file
he loves his lover
she loves her lover
she likes her liker