|
扩展的正则表达式:
扩展正则表达式,顾名思义是对正则表达式的一个扩展,其接受所有的正则表达式,并对grep进行了扩充。如:支持或者表达式 a|b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| 字符匹配:
. : 匹配任意单个字符
[] : 匹配指定范围内的任意单个字符
[^] : 匹配指定范围外的任意单个字符
次数匹配:
* : 任意次
? :0或1次,表示其左侧字符可有可无
+: 至少1次
{m}:精确匹配m次;
{m,n}:至少m次,至多次;
{m,}:至少m次;
{0,n}:至多次;
位置锚定:
^ : 锚定行首
$ : 锚定行尾
\<, \b : 词首锚定
\>, \b : 词尾锚定
分组:()
引用:\1, \2, ...
或者:
a|b:a或者b (或者两侧的所有内容)
|
命令:
grep -E PATTERN FILE...
egrep PATTERN FILE...
grep -E = egrep
例:
1
2
3
4
5
6
7
8
| 创建grep.txt
abc
abbbc
ababc
c
abab
ac
dbabc
|
a?c 匹配0或1次
1
2
3
4
5
6
7
| [iyunv@1inux tmp]# egrep --color=auto "a?c" grep.txt
abc
abbbc
ababc
c
ac
dbabc
|
+: 至少1次
1
2
3
4
5
| [iyunv@1inux tmp]# egrep "b+c" grep.txt
abc
abbbc
ababc
dbabc
|
{m} :精确匹配m次
1
2
| [iyunv@1inux tmp]# egrep "b{3}c" grep.txt
abbbc
|
^: 行首锚定:
1
2
| [iyunv@1inux tmp]# egrep "^c" grep.txt
c
|
$:锚定行尾
1
2
| [iyunv@1inux tmp]# egrep "shutdown$" /etc/passwd
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
|
显示当前系统上root、fedora或user1用户的默认shell;
1
2
3
4
| [iyunv@1inux tmp]# egrep "^(root|fedora|user1)" /etc/passwd | cut -d: -f7
/bin/bash
/bin/bash
/bin/bash
|
显示/boot/grub/grub.conf中以至少一个空白字符开头的行;
1
2
3
4
| [iyunv@1inux tmp]# egrep "^[[:space:]]+" /boot/grub/grub.conf
root (hd0,0)
kernel /vmlinuz-2.6.32-504.el6.x86_64 ro root=/dev/mapper/vg0-root rd_NO_LUKS rd_NO_DM LANG=en_US.UTF-8 rd_LVM_LV=vg0/swap rd_NO_MD SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=vg0/root KEYBOARDTYPE=pc KEYTABLE=us rhgb crashkernel=auto quiet rhgb quiet
initrd /initramfs-2.6.32-504.el6.x86_64.img
|
|
|