基础正则表达式
正则表达式是用来在文件中匹配符合条件的字符串,正则是包含匹配。grep awk sed等命令
通配符 用来匹配符合条件的文件名 * ? [] 完全匹配 ls find cp使用的是通配符
基础正则表达式
-
- 前一个字符匹配0次或任意多次
- . 匹配除了换行符外任意一个字符
- ^ 匹配行首
- $匹配行尾
- []匹配中括号中指定的任意一个字符
- [^]匹配除中括号中指定的任意一个字符
- \ 转义符
- {n}表示其前面的字符恰好出现n次
- {n,}表示其前面的字符出现不小于n次
10.{n,m}表示其前面的字符至少出现n次最多m次
在这个文档里进行下面的操作
[root@tomcat ~]# vim test_rule.txt
Mr.Li Ming said:
he was the honest man in LampBrother
123despise him.
But since Mr. Shenchao came
he never saaaid those words
55555nice!
because.actuaaaaaly,
Mr. shenchao is the most honest man!
Later.Mr.Li ming soid his hot body
*** 前一个字符匹配0次或任意多次**
匹配所有内容,包括空白行
[root@tomcat ~]# grep "a*" test_rule.txt
匹配包含至少一个a
[root@tomcat ~]# grep "aa*" test_rule.txt
Mr.Li Ming said:
he was the honest man in LampBrother
But since Mr. Shenchao came
he never saaaid those words
because.actuaaaaaly,
Mr. shenchao is the most honest man!
Later.Mr.Li ming soid his hot body
匹配两个至少连续a
[root@tomcat ~]# grep "aaa*" test_rule.txt
he never saaaid those words
because.actuaaaaaly,
“.”匹配除了换行符外任意一个字符
"s…d"会匹配在s和d 这两个字母之间一定有两个字符的单词
[root@tomcat ~]# grep "s..d" test_rule.txt
Mr.Li Ming said:
Later.Mr.Li ming soid his hot body
匹配在s和d字母之间有任意字符
[root@tomcat ~]# grep "s.*d" test_rule.txt
Mr.Li Ming said:
he never saaaid those words
Later.Mr.Li ming soid his hot body
匹配所有内容
[root@tomcat ~]# grep ".*" test_rule.txt
Mr.Li Ming said:
he was the honest man in LampBrother
123despise him.
But since Mr. Shenchao came
he never saaaid those words
55555nice!
because.actuaaaaaly,
Mr. shenchao is the most honest man!
Later.Mr.Li ming soid his hot body
^ 匹配行首 $匹配行尾
匹配大写M 开头的行
[root@tomcat ~]# grep "^M" test_rule.txt
Mr.Li Ming said:
Mr. shenchao is the most honest man!
匹配以y结尾的行
[root@tomcat ~]# grep "y$" test_rule.txt
Later.Mr.Li ming soid his hot body
匹配空白行
[root@tomcat ~]# grep -n "^$" test_rule.txt
4:
8:
11:
“[]”匹配中括号中指定的任意一个字符,只匹配一个字符
[root@tomcat ~]# grep -n "s[ao]id" test_rule.txt
1:Mr.Li Ming said:
12:Later.Mr.Li ming soid his hot body
包含数字的行
[root@tomcat ~]# grep -n "[0-9]" test_rule.txt
3:123despise him.
7:55555nice!
匹配以数字开头的行
[root@tomcat ~]# grep "^[0-9]" test_rule.txt
123despise him.
55555nice!
“[^]”匹配除中括号的字符以外的任意一个字符
匹配不以数字开头的行
[root@tomcat ~]# grep "^[^0-9]" test_rule.txt
Mr.Li Ming said:
he was the honest man in LampBrother
But since Mr. Shenchao came
he never saaaid those words
because.actuaaaaaly,
Mr. shenchao is the most honest man!
Later.Mr.Li ming soid his hot body
转义符
匹配以.结尾的行
[root@tomcat ~]# grep "\.$" test_rule.txt
123despise him.
{n}表示其前面的字符恰好出现n次
匹配a字符连续出现三次的字符串
[root@tomcat ~]# grep "a\{3\}" test_rule.txt
he never saaaid those words
because.actuaaaaaly,
匹配最少用连续三个数字开头的行
[root@tomcat ~]# grep "^[0-9]\{3,\}[a-z]" test_rule.txt
123despise him.
55555nice!
.{n,m}表示其前面的字符至少出现n次最多m次
s和a之间最少有一个a最多有三个a
[root@tomcat ~]# grep "sa\{1,3\}" test_rule.txt
Mr.Li Ming said:
he never saaaid those words