shell腳本之正則表達式

一、基礎正則表達式實例:
元字符:
shell腳本之正則表達式
在Linux系統中常見的文件處理工具中grep和sed支持基礎正則表達式。

grep命令選項:

      -i:查找時不區分大小寫;
      -v:查找時反向輸出,如查找不包含某些字符的內容;
      -n:表示查找出結果後顯示行號;

這三個選項可以結合使用,如“-in”,查找時不區分大小寫並顯示行號。
示例:

[root@localhost ~]# grep -n 'the' test.txt                   #查找test文件中包含字符“the”的行
#可以將選項改爲“-vn”來查找不包含“the”的行。
[root@localhost ~]# grep -n "sh[io]rt" test.txt                   #[io]表示匹配 i 或o的顯示出來
#[ ]中無論有幾個字符都僅代表匹配一個字符即可。
[root@localhost ~]# grep -n 'oo' test.txt                 #查找包含字符“oo”的行。
[root@localhost ~]# grep -n 'ooo*' test.txt              #查找包含至少兩個o以上的字符串。
[root@localhost ~]# grep -n 'o\{2\}' test.txt             #查找包含兩個“o”的字符串。
 [root@localhost ~]# grep -n 'o\{2,5\}' test.txt          #查找包含2~5個o的字符串。
 [root@localhost ~]# grep -n 'o\{2,\}' test.txt             #查找包含兩個以上“o”的字符串。
[root@localhost ~]# grep -n '[^w]oo' test.txt           #查找“oo”前面不是w的字符串。
[root@localhost ~]# grep -n '[^a-z]oo' test.txt          #查找oo前不是小寫字母的行。
[root@localhost ~]# grep -n '[0-9]' test.txt               #查找包含數字的行。
[root@localhost ~]# grep -n '^the' test.txt             #查找以“the”開頭的行。
[root@localhost ~]# grep -n '^[a-z]' test.txt             #查找以小寫字母開頭的行。
[root@localhost ~]# grep -n '^[A-Z]' test.txt            #查找以大寫字母開頭的行。 
[root@localhost ~]# grep -n '^[^a-zA-Z]' test.txt       #查找不以字母開頭的行。

#   “^”在[ ] 號外面表示定位行首,也就是以某些內容開頭,若在[ ]內則表示反向選擇。
[root@localhost ~]# grep -n '\.$' test.txt             #查找以 “ .  ” 結尾的行。
[root@localhost ~]# grep -n 'w..d' test.txt             #查找w開頭,中間兩個未知字符,d結尾的行。
[root@localhost ~]# grep -n 'woo*d' test.txt     #查找w開頭d結尾,中間至少包含一個o的字符串。
[root@localhost ~]# grep -n 'w.*d' test.txt        #查找w開頭d結尾,中間的字符可有可無的字符串。
[root@localhost ~]# grep -n '[0-9][0-9]*' test.txt            #查詢任意數字所在行

二、擴展正則表達式
一般來說基礎正則表達式足以我們使用了,但如果想要簡化整個指令,那麼就可以使用擴展正則表達式,如果使用擴展正則表達式,需要使用egrep或awk命令,常見的擴展正則表達式的元字符主要包括如下幾個:
shell腳本之正則表達式

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