Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Linux 正則表達式入門:grep 與 BRE/ERE 用法大全

Linux 文本處理三劍客是 grep(文本過濾)、sed(行編輯器,stream editor)、awk(文本報告生成器,Linux 上的實作為 gawk)。本文聚焦 grep 與正則表達式。

grep 之名源自 Global search REgularexpression and Print out the line:它依據使用者提供的「模式」逐行搜尋目標文本,把匹配的行印出來。模式由正則元字符與普通字元組成,而所謂元字符,就是不表示字面意義、用來表達通配或控制功能的字符,分為基本正則(BRE)與擴展正則(ERE)兩類。

grep 常用選項

grep [OPTIONS] PATTERN [FILE...]
  • --color=auto:高亮匹配字串
  • -v:反向選取,顯示未匹配的行
  • -i:忽略大小寫
  • -o:只顯示被匹配到的字串本身
  • -q:靜默模式,不輸出
  • -E:使用擴展正則

基本正則的元字符

字元匹配:. 任意單一字元;[] 指定範圍內任一單一字元;[^] 排除指定範圍;還有 [:lower:]、[:upper:]、[:digit:]、[:alnum:]、[:space:] 等字元類別。

次數匹配(放在要限制的字元後面):* 任意次、\? 0 或 1 次、\+ 1 次以上、\{m\} 恰好 m 次、\{m,n\} 至少 m 至多 n、\{0,n\} 至多 n、\{m,\} 至少 m;.* 則可匹配任意長度的任意字元。

位置錨定:^ 行首、$ 行尾、\< 或 \b 詞首、\> 或 \b 詞尾、^$ 代表空白行。

分組與後向引用:\(\) 把括號內模式匹配到的內容存進 \1、\2 等變數(依左括號出現順序編號),可用來引用前面分組已匹配到的字元。

grep 家族

  • grep:基本正則;grep -E:擴展正則;grep -F:不支援正則
  • egrep:等同 grep -E;fgrep:等同 grep -F

實例演練

# 1. 顯示 /etc/passwd 中以 bash 結尾的行
grep --color=auto 'bash$' /etc/passwd

# 2. 顯示含兩位或三位數的行
grep --color=auto "[[:digit:]]\{2,3\}" /etc/passwd

# 3. 顯示 netstat 結果中以 LISTEN 加 0~多個空白結尾的行
netstat -tan | egrep 'LISTEN[[:space:]]*$'

# 4. 建立 bash、testbash、busher 與 nologin 使用者後,
#    找出用戶名與其 shell 名相同的行(後向引用)
useradd bash; useradd testbash; useradd busher; useradd -s /sbin/nologin nologin
grep "\(bash\).*\1" /etc/passwd

# 5. 顯示 root、centos、user1 的 UID 與 shell
egrep '^root|^centos|^user1' /etc/passwd | cut -d: -f3,7
egrep --color=auto '(^\<root\>|^\<centos\>|^\<user1\>)' /etc/passwd

# 6. 找出 functions 檔中「單詞後接一組小括號」的行
grep '.*()' /etc/rc.d/init.d/functions

# 7. 從路徑中取出基名與目錄名
echo /etc/passwd | egrep -o "[[:alnum:]]+\/?$"
echo /etc/passwd/ | egrep -o "^\/.*\/"

# 8. 找出 ifconfig 輸出中 1-255 之間的數字
ifconfig | egrep '\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>'
Copyright © Linux教程網 All Rights Reserved