您的位置:首页 > 其它

正则表达式 三

2019-06-14 09:08 169 查看

5)基本元字符 +、?、 —— 目标出现的次数*
以/etc/rc.local文件为例:

[root@svr5 ~]# cat /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

touch /var/lock/subsys/local

输出包括 f、ff、ff、……的行,即“f”至少出现一次:

[root@svr5 ~]# egrep 'f+' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

输出包括init、initial的行,即末尾的“ial”最多出现一次(可能没有):

[root@svr5 ~]# egrep 'init(ial)?' /etc/rc.local
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

输出包括stu、stuf、stuff、stufff、……的行,即末尾的“f”可出现任意多次,也可以没有。重复目标只有一个字符时,可以不使用括号:

[root@svr5 ~]# egrep 'stuf*' /etc/rc.local
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

输出所有行,单独的“.*”可匹配任意行(包括空行):

[root@svr5 ~]# egrep '.*' /etc/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

touch /var/lock/subsys/local

输出/etc/passwd文件内“r”开头且以“nologin”结尾的用户记录,即中间可以是任意字符:

[root@svr5 ~]# egrep '^r.*nologin$' /etc/passwd
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin

6)元字符 {} —— 限定出现的次数范围
创建一个练习用的测试文件:

[root@svr5 ~]# vim brace.txt
ab def ghi abdr
dedef abab ghighi
abcab CD-ROM
TARENA IT GROUP
cdcd ababab
Hello abababab World

输出包括ababab的行,即“ab”连续出现3次:

[root@svr5 ~]# egrep '(ab){3}' brace.txt
cdcd ababab
Hello abababab World
输出包括abab、ababab、abababab的行,即“ab”连续出现2~4次:
[root@svr5 ~]# egrep '(ab){2,4}' brace.txt
dedef abab ghighi
cdcd ababab
Hello abababab World
输出包括ababab、abababab、……的行,即“ab”最少连续出现3次:
[root@svr5 ~]# egrep '(ab){3,}' brace.txt
cdcd ababab
Hello abababab World

7)元字符 [] —— 匹配范围内的单个字符
还以前面的测试文件bracet.txt为例:

[root@svr5 ~]# cat brace.txt
ab def ghi abdr
dedef abab ghighi
abcab CD-ROM
TARENA IT GROUP
cdcd ababab
Hello abababab World

输出包括abc、abd的行,即前两个字符为“ab”,第三个字符只要是c、d中的一个就符合条件:

[root@svr5 ~]# egrep 'ab[cd]' brace.txt
ab def ghi abdr
abcab CD-ROM

输出包括大写字母的行,使用[A-Z]匹配连续范围:

[root@svr5 ~]# egrep '[A-Z]' brace.txt
abcab CD-ROM
TARENA IT GROUP
Hello abababab World

输出包括“非空格也非小写字母”的其他字符的行,本例中大写字母和 – 符合要求:

[root@svr5 ~]# egrep '[^ a-zA-Z]' brace.txt
abcab CD-ROM
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: