一、简介
正则就是一些具有特殊含义的符号,例如:* . ^ $
二、grep命令
作用:从文件中过来满足条件的行
格式:grep [选项] 条件 文件名
案例:
#1 创建测试文件
[root@localhost ~]# vim t1.txt
my name is zxhk
i come from hebei
i love linux and python
haha
#test page
hellow world boys
test age # qq 123
asdf asdf qwer q we ##2 从测试文件中过滤出包含 # 的行
[root@localhost ~]# grep "#" t1.txt#3 从测试文件中过滤出包含 zxhk 的行
[root@localhost ~]# grep "zxhk" t1.txt
3、正则符号
符号 | 含义 |
. | 代表任意一个字符 |
* | 代表其前面的字符出现任意次数 |
.* | 表示任意个任意字符 |
^ | 表示的是行首部 |
$ | 表示的是行尾部 |
案例1:关于 . 的案例
#准备测试文件
[root@localhost ~]# vi t1.txt
my name is zxhk
i cme from hebei
i come from hebei
i ciome from hebei
i cioiame from hebei
i love linux and python
haha
#test page
hellow world boys
test age # qq 123
asdf asdf qwer q we ##1 过滤出c和m之间有两个字符的行
[root@localhost ~]# grep "c..m" t1.txt
案例2:关于 * 的案例
# 准备测试文件
[root@localhost ~]# cat t2.txt
a
ab
aab
aaab
aaababa
aaaaaabbbaba
b
bb
bbb#2 过滤出b前面有任意个a的行【可能是0个, 1个 , 或者多个】
[root@localhost ~]# grep "a*b" t2.txt
案例3:过滤出包含字母 l 和 p 的行,而且l要在前
#准备测试文件
[root@localhost ~]# vi t1.txt
my name is zxhk
i cme from hebei
i come from hebei
i ciome from hebei
i cioiame from hebei
qq lp abcd
qq l p abcd
qq laaap abcd
haha
#test page
hellow world boys
test age # qq 123
asdf asdf qwer q we ## 答案
[root@localhost ~]# grep "l.*p" t3.txt
案例4:
#准备测试文件
[root@localhost ~]# vi t1.txt
my name is zxhk
i cme from hebei
root i come from hebei
i ciome from root hebei
i cioiame from hebei root
root
qq lp abcd
qq l p abcd
qq laaap abcd
haha
#test page
hellow world boys
test age # qq 123
asdf asdf qwer q we ##1 过滤出包含root的行
# 答案1:
[root@localhost ~]# grep "root" t4.txt
# 答案2:
[root@localhost ~]# grep ".*root.*" t4.txt#2 过滤出以root为开头的行
[root@localhost ~]# grep "^root" t4.txt#3 过滤出以root为结尾的行
[root@localhost ~]# grep "root$" t4.txt#4 过滤出仅仅有root的行
[root@localhost ~]# grep "^root$" t4.txt
三、练习题
#1 过滤出以#为开头的行
#2 过滤出以#为结尾的行
#3 过滤出以a为开头,以b为结尾,中间包含字母c的行
#4 过滤出倒数第二个字符是c的行
#5 过滤出第二个字符是c的行
答案:
#1 过滤出以#为开头的行
grep "^#" 文件名#2 过滤出以#为结尾的行
grep "#$" 文件名#3 过滤出以a为开头,以b为结尾,中间包含字母c的行
grep "^a.*c.*b$"#4 过滤出倒数第二个字符是c的行
grep "c.$"#5 过滤出第二个字符是c的行
grep "^.c"