1、显示/etc/passwd
文件中不以/bin/bash结尾的行;
grep -v "/bin/bash$" /etc/passwd
2、找出/etc/passwd文件中的两位数或三位数;
grep -E '\<[0-9]{2,3}\>' /etc/passwd
3、找出/etc/rc.d/rc.sysinit或/etc/grub2.cfg文件中,以至少一个空白字符开头,且后面非空白字符的行;
grep '^[[:space:]]\+[^[:space:]]' /etc/grub2.cfg
4、找出"netstat -tan"命令的结果中以’LISTEN’后跟0、1或多个空白字符结尾的行;
netstat -tan | grep 'LISTEN[[:space:]]*$'
5、找出/proc/meminfo文件中,所有以大写或小写S开头的行;至少有三种实现方式;
grep -i "^s" /proc/meminfo
grep "^[sS]" /proc/meminfo
grep -E "^(s|S)" /proc/meminfo
6、显示肖前系统上root、centos或user1用户的相关信息;
grep -E "^(root|centos|user1)\>" /etc/passwd
7、找出/etc/rc.d/init.d/functions文件中某单词后面跟一个小括号的行;提示:以_或者字母开头,然后以()结尾,其实就是我们的shell函数名。
如:
checkpid()
__kill_pids_term_kill_checkpids()
__kill_pids_term_kill()
__pids_var_run()
__pids_pidof()
daemon()
grep -E -o "[_[:alnum:]]+\(\)" /etc/rc.d/init.d/functions
8、使用echo命令输出一绝对路径,使用egrep取出基名;
提示:取出其路径名;类似于对其执行dirname命令的结果;比如/etc/sysconfig/ ,基名是/etc
echo /etc/sysconfig/ | egrep -o "^/.*[^/]" | egrep -o "^/.*/" | egrep -o "^/.*[^/]"
9、找出ifconfig命令结果中的IP地址;
ifconfig | grep -A 2 ens33 | grep -w inet | grep -Eo 't.*n'| cut -d' ' -f2
10、添加用户bash, testbash, basher以及nologin(其shell为/sbin/nologin);而后找出/etc/passwd文件中用户名同shell名的行;
grep -E "^([^:]+\>).*\1$" /etc/passwd
egrep "^(.*):.*\1$" /etc/passwd
试题要求
:按照题目要求写出你的正则表达式,并把输出结果贴出来。
file.txt文件内容:
48 Dec 3BC1977 LPSX 68.00 LVX2A 138
483 Sept 5AP1996 USP 65.00 LVX2C 189
47 Oct 3ZL1998 LPSX 43.00 KVM9D 512
219 dec 2CC1999 CAD 23.00 PLV2C 68
484 nov 7PL1996 CAD 49.00 PLV2C 234
483 may 5PA1998 USP 37.00 KVM9D 644
216 sept 3ZL1998 USP 86.00 KVM9E 23
4
练习:
1 含有“48”字符串的行的总数
grep -i '48' file.txt |wc -l
grep -c 48 file.txt
2 显示含有“48”字符串的所有行的行号
grep -n 48 file.txt
grep -n '48' file.txt
3 精确匹配只含有“48”字符串的行
PS:使用grep抽取精确匹配的一种更有效方式是在抽取字符串后加\ >
grep "48\>" file.txt
4 抽取代码为4 8 4和4 8 3的城市位置
PS:使用[ ]来指定字符串范围
[root@localhost ~]# grep "48[43]" file.txt
483 Sept 5AP1996 USP 65.00 LVX2C 189
484 nov 7PL1996 CAD 49.00 PLV2C 234
483 may 5PA1998 USP 37.00 KVM9D 644
[root@localhost ~]# grep "48[4|3]" file.txt
483 Sept 5AP1996 USP 65.00 LVX2C 189
484 nov 7PL1996 CAD 49.00 PLV2C 234
483 may 5PA1998 USP 37.00 KVM9D 644
5 显示使行首不是4或8
PS:可以在方括号中使用^记号,表示行首不是某字符
grep -v "^[48]" file.txt
grep -c 48 file.txt
[root@XKWB5705 zhaoyj]# grep -v "^[4|8]" file.txt
[root@XKWB5705 zhaoyj]# grep -v "^[48]" file.txt
[root@XKWB5705 zhaoyj]# grep -v "^[4,8]" file.txt
[root@XKWB5705 zhaoyj]# grep "^[^48]" file.txt
#这个是直接最简单的方法
6 显示含有九月份的行
PS :使用-i开关可以屏蔽月份Sept的大小写敏感
grep -i "sept" file.txt
7 显示以K开头,以D结尾的所有代码
PS:点.代表任意一个字符,由于代码是五位字符的字符串,所以中间用三个点表示任意字符
grep -i "K...D" file.txt
8 显示头两个是大写字母,中间两个任意,并以C结尾的代码
PS:[A-Z]表示任意一个大写字母
grep "[A-Z]\{2\}..C" file.txt
9 查询所有以5开始以1996或1998结尾的所有记录
grep "5..199[6,8]" file.txt
grep '5..[1998|1996]' file.txt
grep '5..[19981996]' file.txt
10 取出所有三位数字的记录
grep "\<[0-9][0-9][0-9]\>" file.txt
grep '\<[0-9]\{3\}\>' file.txt
11 取出所有字母与数字组合的记录
[root@localhost ~]# grep '[a-zA-Z0-9]' file.txt
12 取出所有非数字的记录
[root@localhost ~]# grep '[^0-9]' file.txt
13 取出所有非字母的记录
[root@localhost ~]# grep '[0-9]' file.txt