grep及正則表達式

文本查找的需要:

grep,egrep,fgrep

grep:根據模式,搜索文本,並將符合模式的文本行顯示出來。

Pattern:文本字符和正則表達式的元字符組合而成的匹配條件

grep [OPTIONS] PATTERN [FILE...]

 -i:忽略大小寫

  --color:匹配高亮顏色

  -v:顯示沒被匹配到的行

  -o:只顯示被模式匹配到的字符串


正則表達式:GEGular,EXPression,REGEXP

元字符:

.:匹配任意單個字符


匹配次數:

*:匹配其前面的字符任意次

[]:匹配指定範圍內的任意單個字符

[^]:匹配指定範圍外的任意單個字符

[:digit:],[:lower:],[:upper:],[:punct:],[:space:],[:alpha:],[:alnum:]這個是字符集合

用的時候加雙中括號,例如: [[:digit:]]


 a,b,ab,aab,acb,adb,amnb

 a*b

[root@one ~]# grep a*b test.txt

b

ab

aab

acb

adb

amnb

 a.*b

[root@one ~]# grep 'a.*b' test.txt

ab

aab

acb

adb

amnb


\?:匹配其前面的字符1次或0次

[root@one ~]# grep 'a\?b' test.txt

b

ab

aab

acb

adb

amnb


\{m,n\}:匹配其前的字符至少m次,至多n次

  \{1,\}至少一次,多了不限

  \{0,3\}最多3次

[root@one ~]# grep 'a\{1,3\}b' test.txt

ab

aab


位置錨定:

^:錨定行首,此字符後面的任意內容必須出現在行首

[root@one ~]# grep '^r..t' /etc/passwd

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


$:錨定行尾,次字符前面的任意內容必須出現在行尾

[root@one ~]# grep 'b..h$' /etc/passwd

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

vagrant:x:500:500:vagrant:/home/vagrant:/bin/bash

tom:x:501:501::/home/tom:/bin/bash

user3:x:2002:1002:User3,be,110,119:/home/user3:/bin/bash

user4:x:1003:1003:Tony Blare:/home/blare:/bin/bash

user7:x:1006:1006::/home/user7:/bin/bash

apache:x:497:497::/home/apache:/bin/bash

hadoop:x:2003:2003::/home/hadoop:/bin/bash

^$:空白行


\<:其後面的任意字符必須作爲單詞首部出現

\>:其前面的任意字符必須作爲單詞的尾部出現

\b放在單詞前面或者後面,表示錨定詞首或者詞尾


分組:

\(\)

  \(ab\)*

  後項引用

  \1:引用第一個左括號以及與之對應的右括號所包括的所有內容。

  \2:

  \3:


He love his lover.

She like her liker.

He like his lover.

[root@one ~]# grep '\(ab\)*' test.txt


a

b

ab

aab

acb

adb

amnb







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章