二、深入探索 grep 高級查找模式
1、如何檢索一個具有以 ‘-‘ 開頭的的模式?
使用 -e 選項搜索所有匹配 ‘–test–‘ 的結(jié)果。grep 會嘗試把 ‘–test–‘ 作為一個選項解析:
grep -e '--test--' FILENAME
2、如何在grep中使用 OR 的邏輯運(yùn)算 ?
grep -E 'word1|word2' FILENAME
### OR ###
egrep 'word1|word2' FILENAME
或者可以這樣做
grep 'word1\|word2' FILENAME
3、如何在grep中使用 AND 的邏輯運(yùn)算 ?
按照下面的語法顯示所有包含了單詞 ‘word1′ 和 ‘word2′ 的結(jié)果:
grep 'word1' FILENAME | grep 'word2'
或者可以這樣:
grep 'foo.*bar\|word3.*word4' FILENAME
4、如何測試序列?
你可以使用下面的語法測試一個字符在序列中的重復(fù)的次數(shù):
{N}
{N,}
{min,max}
匹配包含兩個字母 v 的字符串結(jié)果:
egrep "v{2}" FILENAME
下面的例子中將檢索文件內(nèi)包含 “col” 和 “cool” 的字符串結(jié)果:
egrep 'co{1,2}l' FILENAME
下面的例子中將匹配至少含有3個字母 c 的結(jié)果:
egrep 'c{3,}' FILENAME
下面的示例將匹配 “91-1234567890″ 格式的手機(jī)號碼(即 “兩位數(shù)字-十位數(shù)字”)
grep "[[:digit:]]\{2\}[ -]\?[[:digit:]]\{10\}" FILENAME
5、如何使 grep 的輸出結(jié)果高亮標(biāo)注?
使用下面例子的語法:
grep --color regex FILENAME
6、如何使 grep 的輸出只顯示匹配的部分而不是整行?
使用下面例子的語法:
grep -o regex FILENAME
三、正則表達(dá)式操作符總結(jié)
正則表達(dá)式 操作符 |
含義 |
. | 匹配任何單個字符。 |
? | 匹配前一個字符0次或1次。 |
* | 匹配前一個字符≥0次。 |
+ | 匹配前一個字符≥1次。 |
{N} | 匹配前一個字符N次。 |
{N,} | 匹配前一個字符≥m次。 |
{N,M} | 匹配前一個字符 N 到 M次。 |
– | 如果在列表中的某個列表或某個范圍內(nèi)的結(jié)束點(diǎn),表示該范圍。 |
^ | 開始標(biāo)記,表示在開始位置匹配一個空字符串。也表示不在列表的范圍內(nèi)的字符。 |
$ | 結(jié)束標(biāo)記。匹配一個空的字符串。 |
\b | 單詞鎖定符。在一個單詞的邊緣位置匹配空字符串。 |
\B | 在一個單詞的非邊緣位置匹配空字符串。 |
\< | 匹配單詞開始的空字符串。 |
\> | 匹配單詞結(jié)尾的空字符串。 |
egrep 即 grep -E ,它把模式作為一個擴(kuò)展的正則表達(dá)式解釋。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.
![]() | ![]() .. 定價:¥45 優(yōu)惠價:¥42 更多書籍 |
![]() | ![]() .. 定價:¥225 優(yōu)惠價:¥213 更多書籍 |