正则表达式 二

知识共享许可协议 Creative Commons

3)基本元字符 ^、$ —— 匹配行首、行尾
输出默认运行级别的配置记录(以id开头的行):

[root@svr5 ~]# egrep '^id' /etc/inittab
id:3:initdefault:

输出主机名配置记录(以HOSTNAME开头的行):

[root@svr5 ~]# egrep '^HOSTNAME' /etc/sysconfig/network
HOSTNAME=svr5.tarena.com

统计本地用户中登录Shell为“/sbin/nologin”的用户个数:

[root@svr5 ~]# egrep -m10 '/sbin/nologin$' /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
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
[root@svr5 ~]# egrep -c '/sbin/nologin$' /etc/passwd
32  									//结合 -c 选项输出匹配的行数

使用 -c 选项可输出匹配行数,这与通过管道再 wc -l的效果是相同的,但是写法更简便。比如,统计使用“/bin/bash”作为登录Shell的正常用户个数,可执行:

[root@svr5 ~]# egrep -c '/bin/bash$' /etc/passwd
26
或者
[root@svr5 ~]# egrep '/bin/bash$' /etc/passwd | wc -l
26

4)基本元字符 . —— 匹配任意单个字符
以/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

输出/etc/rc.local文件内至少包括一个字符(\n换行符除外)的行,即非空行:

[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/rc.local文件内的空行(用 –v 选项将条件取反):

[root@svr5 ~]# egrep -v '.' /etc/rc.local

[root@svr5 ~]#

上述取空行的操作与下列操作效果相同:

[root@svr5 ~]# egrep '^$' /etc/rc.local

[root@svr5 ~]#

猜你喜欢

转载自blog.csdn.net/weixin_44774638/article/details/91947343