首先按照国际惯例介绍一个grep这个工具:

全名为Global Regular Expression Printing,Linux中强大的文本匹配工具(系统自带),能够实现根据指定的模式(pattern)逐行搜索文本内容,并将匹配的行显示出来。


难度指数★★ ☆☆☆  重要指数★★★★★


基本语法为:grep [option]  'pattern' filename  

关于grep的基本参数(option)我们这里不讲,它是很简单的,你可以先去百度一下,这里主要说grep与正则表达式的简单运用。



grep的基本原则:输出匹配字符串的所在行。


基本正则表达式中的元字符:

①.表示任意一个字符                          

②*表示匹配它前面的字符0次或者多次

0次是重点需要注意的,即可以出现0次,就是不出现也是符合的。

③?匹配它前面字符0次或者1次

④^表示匹配行首

⑤$表示匹配行尾


根据以上几个元字符举个例子说明一下:

[root@localhost~] grep ‘^r.*t’  /etc/passwd

root:x:0:0:root:/root/:/bin/bash

rtkit:x:499:499:Realtimekit:/proc/:/sbin/nologin

如果你觉得还不过瘾,OK加上长选项试一下:

[root@localhost~] grep --color  ‘^r.*t’  /etc/passwd

root:x:0:0:root:/root:/bin/bash

rtkit:x:499:499:Realtimekit:/proc/:/sbin/nologin

将匹配的字符串以红颜色来标明。

⑥[]匹配范围内的单个字符;[^]匹配除范围的单个字符

[root@localhost~] grep '1?[a-z]'  test.txt

可以匹配a-z的任意一个字符所在行和1a-1z的任意字符所在行。

⑦单词锚定:\<单词 锚点词首;\>锚定词尾;\<单词\>精确锚定

假设有一个文本test.txt内容为:

1.I like the computer.

2.We lived in the countryside then.

3.To bathe my hands and face in.

4.And indeed this is also what occurred for athena.

词首锚定the

[root@localhost~]  grep --color  '\<the' test.txt

1.I like the computer.

2.We lived in the countryside then.

词尾锚定the

[root@localhost~]  grep --color  'the\>' test.txt

1.I like the computer.

3.To bathe my hands and face in.

精确匹配the

[root@localhost~]  grep --color=auto  '\<the\>' test.txt

1.I like the computer.

可以看到第4句一次匹配都没有,因为单词athena中的the既不在词首也不在次尾也不是单独的单词,所以...

⑧\{n\}匹配前面字符n次;\{n,\}匹配前面字符至少n次;\{n,m\}匹配前面字符n-m次,n为数字。

[root@localhost ~]# grep --color 'ro\{2\}t' /etc/passwd

root:x:0:0:root:/root:/bin/bash

operator:x:11:0:operator:/root:/sbin/nologin

⑨分组匹配\(n\)*,n可以为多个连续的字符。

假设有如下文本test.txt:

abcd

ad

abcdefg

abcbcd

abcbcdefghl

abbccd

好,我们用grep搜索出重复分组的行

[root@localhost~]grep -color ‘a\(bc\)*d‘ test.txt

abcd

ad

abcdefg

abcbcd

abcbcdefghl

假如我们不想要ad,即我们的原意就是想让他匹配bc分组至少一次的,可以这样写:

[root@localhost~]grep  ‘a\(bc\)*d’  test.txt | grep -v ad

⑩简单介绍一下POSIX字符类。

为了保持不同国家的字符编码一致性,POSIX(Portable Operating System Interface)增加了特殊的字符类,以[:classname:]的格式给出。

假如我们要匹配test.txt中的字符串“a (一段空白) bc"我们可以这样写

grep 'a.*bc' test.txt

也可以利用POSIX字段

grep 'a[[:space:]]bc' test.txt

依稀记得.*和[space:]对处理TAB键是有区别的,但是测试又没有发现什么不同,也许是昨晚看资料看的太晚记错了(~﹃~)~zZ

如若以上有什么不对的请恳请指正。

最后祝大家学习愉快!