[root@www script]# grep "google\>" regular.txt
.google is the best tools for search keyword.
[root@www script]# grep "\<google" regular.txt
.google is the best tools for search keyword.
[root@www script]# grep "\<goog" regular.txt
.google is the best tools for search keyword.
[root@www script]# grep "\<goo" regular.txt 模糊匹配关键字
Oh! The soup taste good.
.google is the best tools for search keyword.
gooogle yes!
[root@www script]# grep "goo\>" regular.txt 没有匹配到关键字
[root@www script]# grep "google\>" regular.txt
.google is the best tools for search keyword.
[root@www script]# grep "\<google\>" regular.txt 精确匹配关键字
.google is the best tools for search keyword.
[root@www script]# grep "\<google" regular.txt 精确匹配关键字
.google is the best tools for search keyword.
[root@www script]# grep "google" regular.txt 精确匹配关键字
.google is the best tools for search keyword.
[root@www script]# grep "\<[Gg]oogle" regular.txt
google is the best tools for search keyword.
Google is the best tools for search keyword.
字符类
字符类的搜索:如果我想要搜寻 test 或 taste 这两个单字时,可以发现到,其实她们有共通的 't?st' 存在~这个时候,我可以这样来搜寻:
[root@www ~]# grep -n 't[ae]st' regular.txt
5:I can't finish the test.
7:Oh! The soup taste good.
字符类的反向选择 [^] :如果想要搜索到有 oo 的行,但不想要 oo 前面有 g,如下
[root@www ~]# grep -n '[^g]oo' regular.txt
2:apple is my favorite food.
3:Football game is not use feet only.
9:google is the best tools for search keyword.
11:goooooogle yes!
第 2,3 行没有疑问,因为 foo 与 Foo 均可被接受,但是第 9 行明明有 google 的 goo 啊,别忘记了,因为该行后面出现了 tool 的 too 啊!所以该行也被列出来,也就是说, 9 行里面虽然出现了我们所不要的项目 (goo) 但是由於有需要的项目 (too) , 因此是符合字串搜寻的。
至于第 11 行,同样的,因为 goooooogle 里面的 oo 前面可能是 o ,例如: go(ooo)oogle ,所以,这一行也是符合需求的。
假设我 oo 前面不想要有小写字母,所以我可以这样写 [^abcd....z]oo,但是这样并不方便,由于小写字母的 ASCII 上编码的顺序是连续的, 因此,我们可以这样来写:
[root@www ~]# grep -n '[^a-z]oo' regular.txt
3:Football game is not use feet only.
如果该字节组是连续的,例如大写英文/小写英文/数字等等, 就可以使用[a-z],[A-Z],[0-9]等方式来书写,那么如果我们的要求字串是数字与英文呢? 就将他全部写在一起,变成:[a-zA-Z0-9]。
我们要取得有数字的那一行,就这样:
[root@www ~]# grep -n '[0-9]' regular.txt
5:However, this dress is about $ 3183 dollars.
8:You are the best is mean you are the no. 1. 行首与行尾字节 ^ $
行首字符:如果我想要让 the 只在行首列出呢? 这个时候就得要使用定位字节了!我们可以这样做:
[root@www ~]# grep -n '^the' regular_express.txt
12:the symbol '*' is represented as start. 如果我不想要开头是英文字母,则可以是这样:
[root@www ~]# grep -n '^[^a-zA-Z]' regular.txt
1:"Open Source" is a good mechanism to develop programs.
11:# I am VBird 注意:因为小数点具有其他意义,所以必须要使用转义字符(\)来加以解除其特殊意义!
找出空白行:
[root@www ~]# grep -n '^$' regular_express.txt
5: 因为只有行首跟行尾 (^$),所以,这样就可以找出空白行啦!