grep (global search regular RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。Unix的grep家族包括grep、egrep和fgrep。
相关阅读:
Linux下Shell编程——awk编程 http://www.linuxidc.com/Linux/2013-06/85527.htm
Linux下Shell编程——sed命令基本用法 http://www.linuxidc.com/Linux/2013-06/85526.htm
Linux下Shell编程——grep命令的基本运用 http://www.linuxidc.com/Linux/2013-06/85525.htm
Linux下Shell编程——正则表达式基础与扩展 http://www.linuxidc.com/Linux/2013-06/85523.htm
grep, egrep, fgrep
grep: 默认支持基本正则表达式;
egrep: 扩展正则表达式;
fgrep: 不支持正则表达式元字符,搜索字符串的速度快,等同於grep -F
正则表达式是一类字符所书写的模式(pattern)
元字符:不表示字符本身的意义,而用于额外功能性的描述;
grep [options] 'pattern' FILE
正则表达式:基本正则表达式,扩展正则表达式;
基本正则表达式:贪婪模式(尽可能长地去匹配符合模式的内容)
^:锚定行首的符合条件的内容,用法格式“^pattern”;
$: 锚定行尾的符合条件的内容,用法格式“pattern$”;
.: 匹配任意单个字符
*:匹配紧挨在其前面的字符任意次;
a*b: ab, aab, acb, b
.*: 匹配任意长度的任意字符
[]:匹配指定范围内的任意单个字符
[^]:匹配指定范围外的任意单个字符
\?: 匹配紧挨在其前面的字符0次或1次;
\{m,n\}: 匹配其前面的字符至少m次,至多n次;
\{0,n\}: 至多n次;0-n次;
{m,\}:至少m次
\{m\}: 精确匹配m次;
\<: 锚定词首,用法格式:\<pattern
\>: 锚定词尾,用法格式:pattern\>
\(\): 分组,用法格式: \(pattern\)
grep的选项:
--color=auto 自动为匹配的字符附色
export GREP_COLOR='01;36'
-r: 递归搜索用法同 -d recurse(递归)
-v: 反向选取,只显示不符合模式的行;
-o: 只显示被模式匹配到的字串,而不是整个行;
-i: 不区分字符大小写;
-A #:显示匹配到的行时,顺带显示其后面的#个行;
-B #:前面的#行;
-C #:前后的#行;
-E: 使用扩展的正则表达式
grep -E = egrep
Grep选项应用实例
[root@localhost ~]# nano /tmp/grepr 创建文件,文件内容下面会显示;
[root@localhost ~]# cat /tmp/grepr | grep -v "^$" 反向选择,显示文件中的非空白行
Nichilema
Magezhenxing
nishishui
wolaile
mingtianjian
nihaihaoma
[root@localhost ~]# cat /tmp/grepr | grep --color -i "m" 不区分m的大小写,只要行中有m/M,都将该行显示出来
Nichilema
Magezhenxing
mingtianjian
nihaihaoma
[root@localhost ~]# cat /tmp/grepr | grep --color -o "m"只显含有m的行
m
m
m
[root@localhost ~]# cat -n /tmp/grepr | grep -A 1 --color "wolaile" 若行中含有“wolaile” 则显示该行和它后边的那一行
4wolaile
5mingtianjian
[root@localhost ~]#cat -n /tmp/grepr | grep -B 1 --color "wolaile"若行中含有“wolaile” 则显示该行和它前边的那一行
3nishishui
4wolaile
[root@localhost ~]# cat -n /tmp/grepr | grep -C 1 --color "wolaile" 若行中含有“wolaile” 则显示该行和它前后各一行
3nishishui
4wolaile
5mingtianjian
Grep 正则表达式实例
1,锚定/etc/passwd文件中行首为root的行
# grep “^root” /etc/passwd
2,锚定/etc/passwd文件行尾为sh的行
# grep “sh$” /etc/passwd
3,查找空白行
# grep “^$” /etc/passwd
4,匹配a后面跟了任意单个字符的行
# grep “a.” /etc/passwd
5,匹配a后面跟了任意个a的行
# grep “a*” /etc/passwd
4,匹配a后面跟了任意长度的任意字符,再跟上b的行
# grep “a.*b” /etc/passwd
5,匹配a后面跟了任意个一数字后又跟了任意一���字母的行
# grep “a[0-9][a-zA-Z]” /etc/passwd
6,匹配a后面跟了任意一个数字或字母的行
# grep “a[0-9a-zA-Z]” /etc/passwd
7,匹配0或1个a后面跟了个b的行
# grep “a\?b” /etc/passwd
8,匹配最少一个a,最多3个a后面跟了一个b的行
# grep “a\{1,3\}b” /etc/passwd
9,锚定单词admin的行
# grep “\<admin\>” /etc/passwd
10,匹配自少出现一次ad,最多出现3次ad的行
# grep “\(ab\)\{1,3\}” /etc/passwd
