三分鐘教你輕鬆掌握 grep 命令中的正則表達式

如何在 Linux 系統和類 Unix 的操作系統中使用帶正則表達式的 grep 命令呢?
Linux 系統自帶了支持拓展正則表達式的 GNU 版本 grep 工具。所有的 Linux 系統中默認安裝的都是 GNU 版 grep 。grep 命令被用來檢索一台伺服器或工作站上任何位置的文本信息。
一、快速了解正則表達式
1、如何匹配你要查找的內容?
正則表達式只不過是每個輸入行匹配的模式。模式是一個字元序列。下面都是範例:
例如:「^w1」、「w1|w2」、「[^ ]」。
在 '/etc/passswd' 中檢索 'vivek' 。
grep vivek /etc/passwd
輸出結果案例:
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash vivekgite:x:1001:1001::/home/vivekgite:/bin/sh gitevivek:x:1002:1002::/home/gitevivek:/bin/sh
在任何情況下都搜索 'vivek' (即不區分大小):
grep -i -w vivek /etc/passwd
不區分大小寫地檢索 'vivek' 和 'raj' :
grep -E -i -w 'vivek|raj' /etc/passwd
在最後一個例子中,使用了擴展正則表達式的模式。
固定檢索內容的位置:
你可以使用 ^ 和 $ 符號強制一個正則表達式分別匹配一行的開始或結束的位置。下面的示例顯示以 'vivek' 開頭的文本。
grep ^vivek /etc/passwd
輸出結果示例:
vivek:x:1000:1000:Vivek Gite,,,:/home/vivek:/bin/bash vivekgite:x:1001:1001::/home/vivekgite:/bin/sh
你可以只顯示以 vivek 開頭的文本行。舉例說就是不顯示 vivekgite , vivekg 這樣單詞開頭的。
grep -w ^vivek /etc/passwd
檢索以 'foo' 結尾的文本格式:
grep 'foo$' FILENAME
你還可以用下面這樣的方式搜索空白行:
grep '^$' FILENAME
2、如何匹配具體字元?
匹配 'Vivek' 或 'vivek' :
grep '[vV]ivek' FILENAME
或者可以這樣:
grep '[vV][iI][Vv][Ee][kK]' FILENAME
你可以匹配數字(例如匹配 vivek1 或 Vivek2 ):
grep -w '[vV]ivek[0-9]' FILENAME
你可以匹配兩位數(例如匹配 foo11 , foo12 ):
grep 'foo[0-9][0-9]' FILENAME
不僅僅是數字,你可以匹配字母:
grep '[A-Za-z]' FILENAME
顯示所有包含 "w" 或 "n" 字母的文本行:
grep [wn] FILENAME
在括弧內的表達式中,在「 [: 」和「 :] 」中所附的字元類的名稱:代表屬於該類的所有字元的列表。標準字元類名稱:
- [:alnum:] - 字母數字字元。
- [:alpha:] - 字母順序
- [:blank:] - 空格和製表符。
- [:digit:] - 數字: '0 1 2 3 4 5 6 7 8 9'。
- [:lower:] - 小寫字母:'a b c d e f '。
- [:space:] - 特殊字元:製表符,換行符,垂直製表符、換頁,回車,和空間。
- [:upper:] - 大寫字母:'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'。
在下面這個例子中,匹配所有大寫字母:
grep '[:upper:]' FILENAME
3、如何使用通配符?
你可以用 "." 來代替單個字元。在下面的例子中,查詢了所有以字母 "b" 開頭、字母 "t" 結尾的三個字元的單詞。
grep '\<b.t\>' FILENAME
在上面的例子中,
- \< 在單詞的開始位置匹配空格字元串
- \> 在單詞的結尾匹配空格字元串
檢索並輸出所有兩個字母的結果:
grep '^..$' FILENAME
檢索並顯示所有以 '.' 和數字開頭的結果:
grep '^\.[0-9]' FILENAME
轉義字元'.'
下面的正則表達式查找 IP 地址 192.168.1.254 將不能獲得預期的結果:
grep '192.168.1.254' /etc/hosts
其中三個點都需要被轉義:
grep '192\.168\.1\.254' /etc/hosts
以下示例將只匹配一個地址:
egrep '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}' FILENAME
以下將不分大小寫地匹配單詞 Linux 或 Unix :
egrep -i '^(linux|unix)' FILENAME
二、深入探索 grep 高級查找模式
1、如何檢索一個具有以 '-' 開頭的的模式?
使用 -e 選項搜索所有匹配 '--test--' 的結果。grep 會嘗試把 '--test--' 作為一個選項解析:
grep -e '--test--' FILENAME
2、如何在grep中使用 OR 的邏輯運算 ?
grep -E 'word1|word2' FILENAME ### OR ### egrep 'word1|word2' FILENAME
或者可以這樣做
grep 'word1\|word2' FILENAME
3、如何在grep中使用 AND 的邏輯運算 ?
按照下面的語法顯示所有包含了單詞 'word1' 和 'word2' 的結果:
grep 'word1' FILENAME | grep 'word2'
或者可以這樣:
grep 'foo.*bar\|word3.*word4' FILENAME
4、如何測試序列?
你可以使用下面的語法測試一個字元在序列中的重複的次數:
{N} {N,} {min,max}
匹配包含兩個字母 v 的字元串結果:
egrep "v{2}" FILENAME
下面的例子中將檢索文件內包含 "col" 和 "cool" 的字元串結果:
egrep 'co{1,2}l' FILENAME
下面的例子中將匹配至少含有3個字母 c 的結果:
egrep 'c{3,}' FILENAME
下面的示例將匹配 "91-1234567890" 格式的手機號碼(即 "兩位數字-十位數字")
grep "[[:digit:]]\{2\}[ -]\?[[:digit:]]\{10\}" FILENAME
5、如何使 grep 的輸出結果高亮標註?
使用下面例子的語法:
grep --color regex FILENAME
6、如何使 grep 的輸出只顯示匹配的部分而不是整行?
使用下面例子的語法:
grep -o regex FILENAME
三、正則表達式操作符總結
正則表達式 操作符 |
含義 |
. | 匹配任何單個字元。 |
? | 匹配前一個字元0次或1次。 |
* | 匹配前一個字元≥0次。 |
+ | 匹配前一個字元≥1次。 |
{N} | 匹配前一個字元N次。 |
{N,} | 匹配前一個字元≥m次。 |
{N,M} | 匹配前一個字元 N 到 M次。 |
- | 如果在列表中的某個列表或某個範圍內的結束點,表示該範圍。 |
^ | 開始標記,表示在開始位置匹配一個空字元串。也表示不在列表的範圍內的字元。 |
$ | 結束標記。匹配一個空的字元串。 |
\b | 單詞鎖定符。在一個單詞的邊緣位置匹配空字元串。 |
\B | 在一個單詞的非邊緣位置匹配空字元串。 |
\< | 匹配單詞開始的空字元串。 |
\> | 匹配單詞結尾的空字元串。 |
四、關於 grep 和 egrep
egrep 即 grep -E ,它把模式作為一個擴展的正則表達式解釋。grep 幫助文檔中這樣定義:
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). Traditional egrep did not support the { meta-character, and some egrep implementations support \{ instead, so portable scripts should avoid { in grep -E patterns and should use [{] to match a literal {. GNU grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification. For example, the command grep -E '{1' searches for the two-character string {1 instead of reporting a syntax error in the regular expression. POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.
參考文獻:
- grep and regex 的幫助文檔
- grep 的 info幫助文檔
原文鏈接:http://www.cyberciti.biz/faq/grep-regular-expressions/
本文鏈接:http://www.linuxstory.org/grep-regular-expressions/
Thank you for sharing your thoughts. I truly appreciate your efforts and I am waiting for your further post thank you once again.
my blog – nordvpn coupons inspiresensation
Hi there! This article could not be written much better! Reading through this post reminds me of my previous roommate! He continually kept talking about this. I’ll forward this article to him. Pretty sure he’s going to have a good read. Many thanks for sharing!
A good document for grep!
Thanks! 歡迎關注LinuxStory其他動態和文章!