一、grep文本过滤器
1. 基本介绍
Global search regular expression and print out theline
全面搜索研究正则表达式并显示出来 grep命令是一种强大的文本搜索工具根据用户指定的
“模式”对目标文本进行比配检查,打印匹配到的行,由正则表达式或者字符及基本文本字符所编写的过滤条件。
2. grep中字符的匹配位置设定
grep 匹配条件 处理文件
^关键字 #关键字开头的行
关键字$ #关键字结尾的行
\<关键字 #不再向前扩展
关键字\> #不再向后扩展
\<关键字\> #不再向前后扩展
例如:
[root@sunshine shell]# grep root passwd #匹配有root的行
[root@sunshine shell]# grep ^root passwd #匹配root开头的行
[root@sunshine shell]# grep root$ passwd #匹配root结尾的行
[root@sunshine shell]# grep -i ^root passwd #-i忽略大小写
[root@sunshine shell]# grep -i -E "^root|root$" passwd #-E识别|符号,"|"表示“或”
[root@sunshine shell]# grep -i -E -v "^root|root$" passwd #-v反向过滤
2. grep中字符的匹配次数设定
* #字符出现0-任意次
\? #字符出现0-1次
+ #字符出现0-任意次
{n} #字符出现n次
{m,n} #字符出现m-n次
{
0,n} #字符出现0-n次
{m,} #字符最少出现m次
(xy){n}xy #关键字出现n次
.* #关键字之间匹配任意字符要加-E
例如:
[root@sunshine shell]# grep -E "r*t" file
[root@sunshine shell]# grep -E "r.*t" file #匹配rt之间任意字符的行
[root@sunshine shell]# grep -E "r..." file #匹配r后面有三个字符字符的行
[root@sunshine shell]# grep -E "r...\>" file #匹配r后面有三个字符字符的行,不向后做扩展
[root@sunshine shell]# grep -E "\<r..." file #匹配r后面有三个字符字符的行,不向前做扩展
[root@sunshine shell]# grep -E "\<r...\>" file #匹配r后面有三个字符字符的行,不向前后做扩展
[root@sunshine shell]# grep -E "ro*t" file #匹配rt之间o出现0-任意次的行
[root@sunshine shell]# grep -E "ro?t" file #匹配rt之间o出现0-1次的行
[root@sunshine shell]# grep -E "r0{1,}t" file #匹配rt之间o出现