GREP
简介 #
常用选项 #
模式部分 #
1. 直接输入要匹配的字符串,可以使用fgrep(fast grep)代替来提高查找速度
2. 使用基本正则表达式
* 匹配字符
. :任意字符
[abc] : 表示匹配一个字符,这个字符必须是abc中的一个。
[^123] : 匹配一个除了123以外的字符
[a-zA-Z] : 等价于[[:alpha:]]
[0-9] : 等价于[[:digit:]]
[a-zA-Z0-9] : 等价于 [[:alnum:]]
tab,space : 等价于 [[:space:]]
[A-Z] : [[:upper:]]
[a-z] : [[:lower:]]
标点符号 : [[:punct:]]
# grep "hello." demo.c
# grep "hello[[:upper:]]" demo.c
# grep "hello[^[:upper:]][[:digit:]]" demo.c
# grep "hell[a-z]" demo.c
# grep "hell[a-z][[:punct:]]" demo.c
* 匹配次数:
\{m,n\} : 至少m,至多n次
\? : 0 或 1 次
* : 任意次
# grep "/.*sh" /etc/passwd
# grep "/.\{0,2\}sh" /etc/passwd
# grep -w ".\{0,2\}sh" /etc/passwd
* 位置锚定:
^ : 锚定行首
$ : 锚定行尾: `^$`用于匹配空白行(没有空格)
\b 或 \< : 单词词首
\b 或 \> : 单词词尾
\B : 与\b 相反 `beer/B` 不是以beer结尾
# grep "h" /etc/passwd
# grep "h$" /etc/passwd
# grep "\<sh" /etc/passwd
# grep "\Bsh\b" /etc/passwd
* 分组及引用:
\(string\) : 将string作为一个整体方便后面引用
\n : 第几个引用,0表示本记录,从1开始
# grep "^\(.\{1\}\).*\1$" /etc/passwd
# grep "^\([[:alpha:]]\).*\1$" /etc/passwd
* 分组后不引用 (?:), 参考Reference
* 零宽断言:
(?=pattern) 正向先行断言(正前瞻)
(?<=pattern) 正向后行断言(正后顾)
(?!pattern) 负向先行断言(负前瞻)
(?<!=pattern)负向后行断言(负后顾)
# 我爱祖国,我是祖国的花朵
# 祖国(?=的花朵)
# (?<=我爱)祖国
# 祖国(?!的花朵)
# (?<!我爱)祖国
3. 扩展正则表达式(-E | egrep)
`?` `+` `|` `()` `{}`
外链 #
Reference #
comments powered by Disqus