Shell命令_正则表达式


正则表达式是包含匹配,通配符是完全匹配

基础正则表达式

 

test.txt示例文件

1
2
3
4
5
6
7
8
9
10
11
12
Mr. James said:
he was the honest man in Companyy.
123despire him.
 
But since Miss.Mary came,
she never saaaid thoes words.
5555nice!
 
because ,actuaaaaally,
Mr.James is the most honest man!
 
Later,Miss Mary soid her hot body.



1、*符号的使用(“ *”前一个字符匹配0次,或任意多次)
1
2
3
4
5
6
7
8
9
grep "a*" test_rule.txt
#匹配所有内容,包括空白行
grep "aa*" test_rule.txt
#匹配至少包含有一个a的行
grep "aaa*" test_rule.txt
匹配最少包含两个连续a的字符串
grep "aaaaa*" test_rule.txt
#则会匹配最少包含四个个连续a的字符串

2、.符号的使用(“ .” 匹配除了换行符外任意一个字符)

1
2
3
4
5
6
7
grep "s..d" test_rule.txt
#“ s..d”会匹配在s和d这两个字母之间一定有两个字符的单词
grep "s.*d" test_rule.txt
#匹配在s和d字母之间有任意字符
grep ".*" test_rule.txt
#匹配所有内容

3、“ ^”匹配行首,“ $”匹配行尾

1
2
3
4
5
6
grep "^M" test_rule.txt
#匹配以大写“ M”开头的行
grep "n$" test_rule.txt
#匹配以小写“ n”结尾的行
grep -n "^$" test_rule.txt
#会匹配空白行

4、“ []” 匹配中括号中指定的任意一个字符,只匹配一个字符

1
2
3
4
5
6
grep "s[ao]id" test_rule.txt
#匹配s和i字母中,要不是a、要不是o
grep "[0-9]" test_rule.txt
#匹配任意一个数字
grep "^[a-z]" test_rule.txt
#匹配用小写字母开头的行

5、“ [^]” 匹配除中括号的字符以外的任意一个字符

1
2
3
4
grep "^[^a-z]" test_rule.txt
#匹配不用小写字母开头的行
grep "^[^a-zA-Z]" test_rule.txt
#匹配不用字母开头的行

6、“ \” 转义符

1
2
grep "\.$" test_rule.txt
#匹配使用“ .”结尾的行

7、“ \{n\}”表示其前面的字符恰好出现n次

1
2
3
4
grep "a\{3\}" test_rule.txt
#匹配a字母连续出现三次的字符串
grep "[0-9]\{3\}" test_rule.txt
#匹配包含连续的三个数字的字符串

8、“ \{n,\}”表示其前面的字符出现不小于n次

1
2
grep "^[0-9]\{3,\}[a-z]" test_rule.txt
#匹配最少用连续三个数字开头的行

9、“ \{n,m\}”匹配其前面的字符至少出现n次,最多出现m次

1
2
grep "sa\{1,3\}i" test_rule.txt
#匹配在字母s和字母i之间有最少一个a,最多三个a







posted @ 2016-10-13 10:09    阅读(598)  评论(0编辑  收藏  举报