[Linux Shell学习系列九]正则表达式-2正则应用基础

D18

注:对文中部分实例做了修改。

1. 使用句点.匹配单字符

$ cat list.txt 
1122
112
11222
2211
22111
abdde
abede
bbcde
bbdde

$ grep "112." list.txt  #112后面有一个任意字符
1122
11222

$ grep "d.e" list.txt #d和e中间有一个任意字符
abdde
bbdde

$ grep "2.." list.txt #2后面两个任意字符
11222
2211
22111

2. 使用插入符号^匹配

$ grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

$ grep ^root /etc/passwd #root在行首
root:x:0:0:root:/root:/bin/bash

3. 使用美元符$匹配

$ cat list.txt #包含一个空行
1122
112
11222
2211
22111

abdde
abede
bbcde
bbdde

$ grep -v '^$' list.txt  #用^$匹配空行,用-v排除
1122
112
11222
2211
22111
abdde
abede
bbcde
bbdde

$ grep 'bash$' /etc/passwd #过滤bash结尾的行,找到使用bash作为默认Shell的用户
root:x:0:0:root:/root:/bin/bash

4. 使用星号*匹配

#过滤日志中匹配"kernel: *"的行
# grep "kernel: *." /var/log/messages #kernel:后有0个或多个空格( *),然后.匹配任意字符

grep "\<a.*e\>" list.txt #查找文件中,所有包含单词是字母a开头,e结尾的行
#或者
egrep "\<a.*e\>" list.txt

5. 使用方括号[]匹配

$ grep "[a-z]\{5\}" list.txt  #找出文件中至少有5个连续小写字母的行
#或者
$ egrep "[a-z]{5}" list.txt 

$ grep "[0-9]\+" list.txt #找出文件包含一个或多个数字的行
#或者
$ egrep "[0-9]\+" list.txt

6. 使用问号?匹配

$ cat list.txt 
ab dde
ab   dde
abde

$ grep "ab \?d" list.txt #匹配ab和d之间有0个或1个空格
ab dde
abde
#或者
$ egrep "ab ?d" list.txt
ab dde
abde

7. 使用加号+匹配

$ cat list.txt 
ab dde
ab   dde
abde

$ grep "ab \+d" list.txt #匹配ab和d之间有1个或多个空格
ab dde
ab   dde
#或者
$ egrep "ab +d" list.txt 
ab dde
ab   dde

本节结束

猜你喜欢

转载自www.cnblogs.com/workingdiary/p/12978770.html