学习目标
• grep用法
• 为什么要学习正则表达式?
• 学习更多的元字符
• 元字符的灵活应用。
1. 为什么要学习Regular Expression
1) 模糊、快速匹配数据串
2) 为学习 grep,awk, sed等文本过滤命令作铺垫
3) 编写 高级bash脚本的需要
2. 正则有哪些元字符
[ ] \ ^ $ . | ? * + ( )
3. 基本元字符集及其含义
^ 匹配行首 grep ‘^tcp’ 1.txt
$ 只匹配行尾 grep 'tom$' 1.txt* 一个单字符后紧跟*,匹配 0 个或多个此单字符 grep 'a*' 1.txt
只匹配[ ] 内字符。可以是一个单字符,也可以是字 grep '[0-9a-z]' 1.txt[ ] 符序列。可以使用‘-’表示[ ]内字符序列范围,如
用[ 1 - 5 ]代替[ 1 2 3 4 5 ] \
用来屏蔽一个元字符的特殊含义。因为有时在 s h e grep "[a-z]\." 1.txt\ l l 中一些元字符有特殊含义。\可以使其失去应有意
义。\t \r \n
? 告诉引擎匹配前导字符 0 次或一次 grep 'S?L' 1.txt
+ 告诉引擎匹配前导字符 1 次或多次 grep 'S+L' 1.txt. 只匹配任意单字符 grep 'p.' 1.txt
p a t t e r n \ { n \ } 只用来匹配前面 p a t t e r n 出现次数。n 为次数 grep 'tom\{2\}' 1.txtp a t t e r n \ { n,\ } 只含义同上,但次数最少为 n grep 'tom\{2,\}' 1.txt
p a t t e r n \ { n,m \ } 只含义同上,但 p a t t e r n 出现次数在 n 与 m之间 grep 'tom\{2,8\}' 1.txt
grep更深入的用法
grep结合正则表达式的实际示例
1. 匹配开头和结尾字符
格式:grep { ^string | string $ } filename
示例:
grep ^[a-z]tr filename
grep tr$ filename
2. 匹配整个单词
格式: grep ‘\bword\b’ filename
3. . ? +和 *的用处
格式:grep { … | ? | .*} filename
. 匹配单个字符能匹配空格
* 匹配任意字符或字符串的重复多次
.+ 字符必须出现1次
.? 字符出现0次或1次
示例:
a) .的匹配
b) *的匹配
注意:grep不支持+ ?元字符 必须要加上-E选项
Perl的正则表达-P
c) .* 的贪婪匹配
d) .*? 惰性匹配
4. grep的标签
格式:grep ‘\(str\)\(\)\(\)[other]\1’ filename
示例:grep -n '\(tom\)\(guozi\)..\1' a3.txt –color
搜索文本中出现tom或者guozi所在的行
grep -E '(tom|guozi)' a3.txt --color
5. grep中的pattern搜索
格式1:grep ‘[str]\{1\}’ filename
格式2:grep ‘[str]\{1,\}’ filename
格式3:grep ‘[str]\{1,3}’ filename
格式1举例
grep -n 'tom\{2\}' a3.txt
grep -n '\(tom\)\{2\}' a3.txt
格式2举例——搜索文本中至少包含1次tom的行:
grep -n '\(tom\)\{1,\}' a3.txt --color
格式3举例——搜索文本中出现1~3次包含tom的行:
grep -n '\(tom\)\{1,3\}' a3.txt
以tom开头,连续出现1~3次的行:
grep -n '^\(tom\)\{1,3\}' a3.txt --color