平时使用grep搜索字符串的频率很高,但绝大时候都使用的是最简单的搜索,稍微复杂一点就要先百度。归根接地是对正则表达式的使用不够熟练。
下面总结一下平时工作中用到的正则表达式。
语法
grep [options] [pattern] [file]
options
-a : 不要忽略二进制数据
-c : 计算符合样式的列数
-d <动作> : 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
-e<范本样式>: 指定字符串做为查找文件内容的样式
-E : 将样式为延伸的正则表达式来使用。
-i : 忽略字符大小写的差别。
-n : 在显示符合样式的那一行之前,标示出该行的列数编号。
-r : recurse,递归,作用于该目录下的所有子目录及文件。
-v, : --invert-match 反向匹配,接过滤不包含的
pattern
正则表达式字符串代表匹配规则,一些特殊字符的含义如下:
^ :匹配行开头包括如下字符的行
example:匹配开头是hello的行
grep "^hello" file
$ :匹配行末尾包括如下字符的行
example:匹配结尾是hello的行
grep "$hello" file
. :通配符,表示任何单个字符
example:匹配只有一个字符的行
grep "^.$" file
* :代表重复前一个字符 0 到无穷多次
example: 匹配g开头,g结尾,中间至少含有一个o的行
grep "goo*g" file
\ :转义字符
example:匹配包括字符$的行
grep "\$ file
[ ] :限定范围
example:匹配包括数字的行
grep "[0-9]" file
example:匹配不包括数字的行
grep "[^0-9]" file
{} : 限定重复次数
example: 匹配含有连个o的字符
grep -n "o\{2\}" file
example:匹配g后面有2~5个o的字符串
grep -n 'go\{2,5\}' file
扩展grep(grep -E 或者 egrep)
example: 搜素包含一个或多个3的行
egrep '3+' file
grep -E '3+' file
example: 搜索含有good或者hello的行
egrep "good|hello" file