grep, egrep, fgrep - 列印匹配給定模式的行
總覽 SYNOPSISgrep [options] PATTERN [FILE...]
grep [options] [-e PATTERN | -f FILE] [FILE...]
Grep 搜索以 FILE 命名的文件輸入 (或者是標準輸入,如果沒有指定文件名,或者給出的文件名是 - 的話),尋找含有與給定的模式 PATTERN 相匹配的內容的行。默認情況下, grep 將把含有匹配內容的行列印出來。
另外,也可以使用兩個變種程序 egrep 和 fgrep 。 Egrep 與 grep -E 相同。 Fgrep 與 grep -F 相同。
選項 OPTIONS-A NUM, --after-context=NUM 列印出緊隨匹配的行之後的下文 NUM 行。在相鄰的匹配組之間將會列印內容是 -- 的一行。 -a, --text 將一個二進位文件視為一個文本文件來處理;它與 --binary-files=text 選項等價。 -B NUM, --before-context=NUM 列印出匹配的行之前的上文 NUM 行。在相鄰的匹配組之間將會列印內容是 -- 的一行。 -C NUM, --context=NUM 列印出匹配的行的上下文前後各 NUM 行。在相鄰的匹配組之間將會列印內容是 -- 的一行。 -b, --byte-offset 在輸出的每行前面同時列印出當前行在輸入文件中的字節偏移量。 --binary-files=TYPE 如果一個文件的起始幾個字節表明文件包含二進位數據,那麼假定文件是 TYPE 類型的。默認情況下, TYPE 是 binary ,並且 grep 一般會輸出一個一行的消息說一個二進位文件匹配,或者如果沒有匹配的話就沒有消息輸出。如果類型 TYPE 是 without-match ,那麼 grep 假定二進位文件不會匹配;這樣做與 -I 選項等價。如果類型 TYPE 是 text ,那麼 grep 將一個二進位文件視為文本文件來處理;它與 -a 選項等價。 警告: grep --binary-files=text 可能會輸出二進位的無用內容。如果輸出設備是一個終端,並且終端的驅動將這些輸出中的一些當作命令,可能會帶來惡劣的副作用。 --colour[=WHEN], --color[=WHEN] 在匹配的行周圍以 GREP_COLOR 環境變量中指定的記號來標記。WHEN 可以是 `never', `always', 或是 `auto'。 -c, --count 禁止通常的輸出;作為替代,為每一個輸入文件列印一個匹配的行的總數。如果使用 -v, --invert-match 選項 (參見下面),將是不匹配的行的總數。 -D ACTION, --devices=ACTION 如果輸入文件是一個設備,FIFO 或是套接字 (socket) ,使用動作 ACTION 來處理它。默認情況下,動作 ACTION 是 read ,意味著設備將視為普通文件那樣來讀。如果動作 ACTION 是 skip ,將不處理而直接跳過設備。 -d ACTION, --directories=ACTION 如果輸入文件是一個目錄,使用動作 ACTION 來處理它。默認情況下,動作 ACTION 是 read ,意味著目錄將視為普通文件那樣來讀。如果動作 ACTION 是 skip ,將不處理而直接跳過目錄。如果動作 ACTION 是 recurse , grep 將遞歸地讀每一目錄下的所有文件。這樣做和 -r 選項等價。 -E, --extended-regexp 將模式 PATTERN 作為一個擴展的正則表達式來解釋 (參見下面)。 -e PATTERN, --regexp=PATTERN 使用模式 PATTERN 作為模式;在保護以 - 為起始的模式時有用。 -F, --fixed-strings 將模式 PATTERN 視為一個固定的字符串的列表,用新行 (newlines) 分隔,只要匹配其中之一即可。 -P, --perl-regexp 將模式 PATTERN 作為一個 Perl 正則表達式來解釋。 -f FILE, --file=FILE 從文件 FILE 中獲取模式,每行一個。空文件含有0個模式,因此不匹配任何東西。 -G, --basic-regexp 將模式 PATTERN 作為一個基本的正則表達式 (參見下面) 來解釋。這是默認值。 -H, --with-filename 為每個匹配列印文件名。 -h, --no-filename 當搜索多個文件時,禁止在輸出的前面加上文件名前綴。 --help 輸出一個簡短的幫助信息。 -I 處理一個二進位文件,但是認為它不包含匹配的內容。這和 --binary-files=without-match 選項等價。 -i, --ignore-case 忽略模式 PATTERN 和輸入文件中的大小寫的分別。 -L, --files-without-match 禁止通常的輸出;作為替代,列印出每個在通常情況下不會產生輸出的輸入文件的名字。對每個文件的掃描在遇到***個匹配的時候就會停止。 -l, --files-with-matches 禁止通常的輸出;作為替代,列印出每個在通常情況下會產生輸出的輸入文件的名字。對每個文件的掃描在遇到***個匹配的時候就會停止。 -m NUM, --max-count=NUM 在找到 NUM 個匹配的行之後,不再讀這個文件。如果輸入是來自一個普通文件的標準輸入,並且已經輸出了 NUM 個匹配的行, grep 保證標準輸入被定位於退出時的***一次匹配的行之後,不管是否指定了要輸出緊隨的下文的行。這樣可以使一個調用程序恢復搜索。當 grep 在 NUM 個匹配的行之後停止,它會輸出任何緊隨的下文的行。當使用了 -c 或 --count 選項的時候, grep 不會輸出比 NUM 更多的行。當指定了 -v 或 --invert-match 選項的時候, grep 會在輸出 NUM 個不匹配的行之後停止。 --mmap 如果可能的話,使用 mmap(2) 系統調用來讀取輸入,而不是默認的 read(2) 系統調用。在一些情況下, --mmap 提供較好的性能。但是,如果一個輸入文件在 grep 正在操作時大小發生變化,或者如果發生了一個 I/O 錯誤, --mmap 可能導致不可知的行為 (包括core dumps)。 -n, --line-number 在輸出的每行前面加上它所在的文件中它的行號。 -o, --only-matching 只顯示匹配的行中與 PATTERN 相匹配的部分。 --label=LABEL 將實際上來自標準輸入的輸入視為來自輸入文件 LABEL 。這對於 zgrep 這樣的工具非常有用,例如: gzip -cd foo.gz |grep --label=foo something --line-buffering 使用行緩衝,it can be a performance penality. -q, --quiet, --silent 安靜。不向標準輸出寫任何東西。如果找到任何匹配的內容就立即以狀態值 0 退出,即使檢測到了錯誤。參見 -s 或 --no-messages 選項。 -R, -r, --recursive 遞歸地讀每一目錄下的所有文件。這樣做和 -d recurse 選項等價。 --include=PATTERN 僅僅在搜索匹配 PATTERN 的文件時在目錄中遞歸搜索。 --exclude=PATTERN 在目錄中遞歸搜索,但是跳過匹配 PATTERN 的文件。 -s, --no-messages 禁止輸出關於文件不存在或不可讀的錯誤信息。對於可移植性需要注意:與 GNU grep 不同,傳統的 grep 不遵守 POSIX.2 規範,因為傳統的 grep 缺少一個 -q 選項,而它的 -s 選項與 GNU grep 的 -q 選項行為相似。需要可移植到傳統 grep 的 shell 腳本應當避免使用 -q 和 -s 選項,而應當將輸出重定向到 /dev/null 。 -U, --binary 將文件視為二進位。默認情況下,在 MS-DOS 和 MS-Windows 系統中, grep 通過從文件中讀取頭部的 32kB 內容來判斷它的文件類型。如果 grep 判斷文件是一個文本文件,它將原始文件內容中的 CR 字符去除 (使得含有 ^ 和 $ 的正則表達式可以正常工作)。指定 -U 將不進行這些工作,而使所有文件保持不變地讀取並傳遞給匹配機制。如果文件是一個以 CR/LF 換行的文本文件,這樣作將導致一些正則表達式失敗。這個選項在 MS-DOS 和 MS-Windows 之外的系統中無效。 -u, --unix-byte-offsets 報告 Unix 風格的字節偏移量。這個開關使得 grep 報告字節偏移量時,將文件作為 Unix 風格的文本文件看待,也就是說將 CR 字符去掉。這將產生與在一臺 Unix 主機上運行 grep 完全相同的結果。除非同時使用 -b 選項,否則這個選項無效。這個選項在 MS-DOS 和 MS-Windows 之外的系統中無效。 -V, --version 向標準錯誤輸出列印 grep 的版本號。版本號應當包含在所有的 bug 報告中 (參見下面)。 -v, --invert-match 改變匹配的意義,只選擇不匹配的行。 -w, --word-regexp 只選擇含有能組成完整的詞的匹配的行。判斷方法是匹配的子字符串必須是一行的開始,或者是在一個不可能是詞的組成的字符之後。與此相似,它必須是一行的結束,或者是在一個不可能是詞的組成的字符之前。詞的組成字符是字母,數字,還有下劃線。 -x, --line-regexp 只選擇能匹配完整一行的匹配。 -y -i 的同義詞,廢棄不用。 -Z, --null 輸出一個全零字節 (ASCII 碼中的 NUL 字符) 而不是一般情況下輸出在文件名之後的字符。例如, grep -lZ 在每個文件名之後輸出一個全零字節而不是普通的新行符。這個選項使得輸出清楚明白,即使文件名的表示中包含特殊字符比如新行符。這個選項可以與命令 find -print0, perl -0, sort -z, 和 xargs -0 一起使用,來處理任意的文件名,即使是那些含有新行符的文件名。 正則表達式 REGULAR EXPRESSIONS一個正則表達式是一個描述了一個字符串集合的模式。正則表達式的構造類似於算術表達式,使用各種各樣的操作符來將更小的表達式連在一起。
Grep 能理解兩種不同版本的正則表達式語法:``basic'' 和 ``extended''。在 GNU grep 中,兩種語法可以實現的功能是沒有區別的。在其他實現中,基本 (basic) 正則表達式表達能力要弱一點。下面的描述適用於擴展的 (extended) 正則表達式,它與基本正則表達式的區別會在***做一個總結。
基本的構造塊是匹配單個字符的正則表達式。大部分字符,包括所有字母和數字,是匹配它們自身的正則表達式。任何具有特殊含義的元字符可以通過前置一個反斜槓來引用。(may be quoted by preceding it with a backslash.)
方括號表達式 (bracket) 是一個字符序列,放在 [ 和 ] 當中。它匹配序列中的任何一個字符;如果序列中的***個字符是脫字符 (caret) ^ 那麼它匹配 不在 序列中的任何一個字符。例如,正則表達式 [0123456789] 匹配任何一個數字。
在方括號表達式之中,一個 範圍表達式 (range) 由兩個字符組成,中間用一個連字符 (hyphen) 分隔。它匹配在這兩個字符之間的任何一個字符,使用本地化的序列順序和字符集。(that sorts between the two characters,inclusive, using the locale's collating sequence and character set.) 例如,在默認的 C locale中, [a-d] 與 [abcd] 等價。典型的,許多 locale 將字符以字典順序排序,在這些 locale 中, [a-d] 不與 [abcd] 等價;例如它可能與 [aBbCcDd] 等價。要獲得傳統的對方括號表達式的解釋,可以設定環境變量 LC_ALL 值為 C 來使用 locale C 。
***,在方括號表達式中有一些預定義的字符類,如下所示。它們的名字是自說明的,它們是 [:alnum:](字母和數字), [:alpha:](字母), [:cntrl:](), [:digit:](數字), [:graph:](), [:lower:](小寫字母), [:print:](可列印字符), [:punct:](), [:space:](空格), [:upper:](大寫字母), 和 [:xdigit:] 。例如, [[:alnum:]] 意思是 [0-9A-Za-z] ,但是後一種表示方法依賴於 locale C 和ASCII 字符編碼,而前一種是與 locale 和字符集無關的。(注意這些字符類名中的方括號也是符號名稱的一部分,必須包含在用來為序列定界的方括號之中。)
大多數元字符處於序列中時會失去它們的特殊意義。為了包含一個字面意義 (literal) 的 ] ,需要將它放在序列的最前。與此相似,為了包含一個字面意義 (literal) 的 ^ ,需要將它放在除了序列最前之外的其他位置。***,為了包含一個字面意義 (literal) 的 - ,需要將它放在序列***。
句點符 (period) . 匹配任何一個字符。符號 \w 是 [[:alnum:]] 的同義詞, \W 是 [^[:alnum]] 的同義詞。
脫字符 (caret) ^ 和美元標記 (dollar) $ 分別是匹配一行的首部和尾部的空字串的元字符。符號 \< 和 \> 分別是匹配一個詞的首部和尾部的空字串的元字符。符號 \b 匹配一個詞邊緣 (edge) 的空字串,符號 \B 匹配 不 處於一個詞的邊緣的空字串。
一個正則表達式後面可以跟隨多種重複操作符之一。
? 先前的項是可選的,最多匹配一次。 * 先前的項可以匹配零次或多次。 + 先前的項可以匹配一次或多次。 {n} 先前的項將匹配恰好 n 次。 {n,} 先前的項可以匹配 n 或更多次。 {n,m} 先前的項將匹配至少 n 詞,但是不會超過 m 次。兩個正則表達式可以連接到一起;得出的正則表達式可以匹配任何由兩個分別匹配連接前的子表達式的子字符串連接而成的字符串。
兩個正則表達式可以用中綴操作符 | 聯合到一起,得出的正則表達式可以匹配任何匹配聯合前的任何一個子表達式的字符串。
重複操作符的優先級比連接高,接下來又比選擇的優先級高。一個完整的子表達式可以用圓括號 (parentheses) 括住來超越這些優先級規則。(to override these precedence rules.)
反向引用 \n 中, n 是一個數字,匹配正則表達式中,以第 n 個圓括號括住的子表達式已匹配的子字符串。
在基本正則表達式中,元字符 ?, +, {, |, (, 和 ) 喪失了它們的特殊意義;作為替代,使用加反斜槓的 (backslash) 版本 \?, \+, \{, \|, \(, 和 \) 。
傳統的 egrep 不支持元字符 { ,並且一些 egrep 的實現通過支持 \{ 來代替它,因此可移植的腳本應當避免在 egrep 中使用 { 模式,應當使用 [{] 來匹配一個字面意義 (literal) 的 { 。
GNU egrep 通過假設如果 { 處於 an invalid interval specification 的起始,就不是一個特殊字符,來支持傳統的用法。例如,shell 命令 egrep '{1' 將會搜索這個兩字符的字符串 {1 而不是報告在正則表達式中發生了語法錯誤。POSIX.2 允許這個行為,將其視為一個擴展,但是可移植的腳本應當避免使用它。
環境變量 ENVIRONMENT VARIABLESGrep 的行為受下列環境變量影響。
一個 locale LC_foo 是通過按下面的順序, LC_ALL, LC_foo, LANG, 檢查這三個環境變量的取值而確定的。設置了的***個變量指定了 locale。例如,如果 LC_ALL 沒有設置,但是 LC_MESSAGES 設置為 pt_BR ,那麼巴西的葡萄牙語 (Brazilian Portuguese) 將用作 LC_MESSAGES locale 的值。如果沒有設置這其中任何一個環境變量,或者沒有安裝所設置的 locale 目錄,或者如果 grep 沒有將國家和語言支持 (national language support (NLS)) 編譯在內,將默認使用 locale C。
GREP_OPTIONS 這個變量指定了將放在所有顯式指定的選項之前的默認選項。例如,如果 GREP_OPTIONS 是 '--binary-files=without-match --directories=skip' 的話, grep 將像已經在任何顯式指定的選項之前指定了 --binary-files=without-match 和 --directories=skip 選項那樣來運作。選項以空白 (whitespace) 分隔。一個反斜槓 (backslash) 使得下一個字符轉義 (escape),因此可以用來指定一個含有空白或者反斜槓的選項。 GREP_COLOR 指定用來高亮顯示的標記。 LC_ALL, LC_COLLATE, LANG 這些變量指定了 locale LC_COLLATE ,決定了解釋類似 [a-z] 的範圍表達式時的序列順序 (collating sequence) 。 LC_ALL, LC_CTYPE, LANG 這些選項指定了 locale LC_CTYPE ,決定了字符的類型,例如,哪些字符是空白 (whitespace) 。 LC_ALL, LC_MESSAGES, LANG 這些選項指定了 locale LC_MESSAGES ,決定了 grep 的消息使用的語言。默認的 locale C 使用美國英語的消息。 POSIXLY_CORRECT 如果設置了的話, grep 將像 POSIX.2 要求的那樣來運作;否則, grep 將像其他 GNU 程序一樣來運作。POSIX.2 要求文件名之後的選項必須視為文件名;默認情況下,這些選項被交換到操作數列表的前面,被當作選項來處理。同時, POSIX.2 要求不可識別的選項在診斷消息中表示為 ``illegal'',但是既然它們沒有真正觸犯法律,因此默認情況下它們在診斷 (diagnose) 消息中表示為 ``invalid''。 POSIXLY_CORRECT 同時禁止了下面描述的 _N_GNU_nonoption_argv_flags_。 _N_GNU_nonoption_argv_flags_ (這裡 N 是 grep's 數字形式的進程ID。) 如果這個環境變量的值的第 i 個字符是 1 ,那麼不將 grep 的第 i 個操作數視為一個選項,即使它看上去像。shell 可以將這個變量設置在它運行的每個命令的環境中,指定哪個操作數是文件名通配符擴展的結果,因此不應當被視為選項。這個行為只有在使用 GNU C 庫時有效,並且只有在 POSIXLY_CORRECT 沒有設置的時候。 NAMEgrep, egrep, fgrep - print lines matching a pattern
SYNOPSISgrep [options] PATTERN [FILE...]
grep [options] [-e PATTERN | -f FILE] [FILE...]
Grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -E. Fgrep is the same as grep -F.
OPTIONS-A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing -- between contiguous groups of matches. -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing -- between contiguous groups of matches. -C NUM, --context=NUM Print NUM lines of output context. Places a line containing -- between contiguous groups of matches. -b, --byte-offset Print the byte offset within the input file before each line of output. --binary-files=TYPE If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep --binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. --colour[=WHEN], --color[=WHEN] Surround the matching string with the marker find in GREP_COLOR environment variable. WHEN may be `never', `always', or `auto' -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, which means that directories are read just as if they were ordinary files. If ACTION is skip, directories are silently skipped. If ACTION is recurse, grep reads all files under each directory, recursively; this is equivalent to the -r option. -E, --extended-regexp Interpret PATTERN as an extended regular expression (see below). -e PATTERN, --regexp=PATTERN Use PATTERN as the pattern; useful to protect patterns beginning with -. -F, --fixed-strings Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. -P, --perl-regexp Interpret PATTERN as a Perl regular expression. -f FILE, --file=FILE Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. -G, --basic-regexp Interpret PATTERN as a basic regular expression (see below). This is the default. -H, --with-filename Print the filename for each match. -h, --no-filename Suppress the prefixing of filenames on output when multiple files are searched. --help Output a brief help message. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. -i, --ignore-case Ignore case distinctions in both the PATTERN and the input files. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. --mmap If possible, use the mmap(2) system call to read input, instead of the default read(2) system call. In some situations, --mmap yields better performance. However, --mmap can cause undefined behavior (including core dumps) if an input file shrinks while grep is operating, or if an I/O error occurs. -n, --line-number Prefix each line of output with the line number within its input file. -o, --only-matching Show only the part of a matching line that matches PATTERN. --label=LABEL Displays input actually coming from standard input as input coming from file LABEL. This is especially useful for tools like zgrep, e.g. gzip -cd foo.gz |grep --label=foo something --line-buffered Use line buffering, it can be a performance penality. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -R, -r, --recursive Read all files under each directory, recursively; this is equivalent to the -d recurse option. --include=PATTERN Recurse in directories only searching file matching PATTERN. --exclude=PATTERN Recurse in directories skip file matching PATTERN. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Portability note: unlike GNU grep, traditional grep did not conform to POSIX.2, because traditional grep lacked a -q option and its -s option behaved like GNU grep's -q option. Shell scripts intended to be portable to traditional grep should avoid both -q and -s and should redirect output to /dev/null instead. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses the file type by looking at the contents of the first 32KB read from the file. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -u, --unix-byte-offsets Report Unix-style byte offsets. This switch causes grep to report byte offsets as if the file were Unix-style text file, i.e. with CR characters stripped off. This will produce results identical to running grep on a Unix machine. This option has no effect unless -b option is also used; it has no effect on platforms other than MS-DOS and MS-Windows. -V, --version Print the version number of grep to standard error. This version number should be included in all bug reports (see below). -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. -x, --line-regexp Select only those matches that exactly match the whole line. -y Obsolete synonym for -i. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. REGULAR EXPRESSIONSA regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.
Grep understands two different versions of regular expression syntax: ``basic'' and ``extended.'' In GNU grep, there is no difference in available functionality using either syntax. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards.
The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash.
A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit.
Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C.
Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means [0-9A-Za-z], except the latter form depends upon the C locale and the ASCII character encoding, whereas the former is independent of locale and character set. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket list.) Most metacharacters lose their special meaning inside lists. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last.
The period . matches any single character. The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum]].
The caret ^ and the dollar sign $ are metacharacters that respectively match the empty string at the beginning and end of a line. The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word.
A regular expression may be followed by one of several repetition operators:
? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {n,m} The preceding item is matched at least n times, but not more than m times.Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated subexpressions.
Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either subexpression.
Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole subexpression may be enclosed in parentheses to override these precedence rules.
The backreference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression.
In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).
Traditional egrep did not support the { metacharacter, and some egrep implementations support \{ instead, so portable scripts should avoid { in egrep patterns and should use [{] to match a literal {.
GNU egrep 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 shell command egrep '{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.
ENVIRONMENT VARIABLESGrep's behavior is affected by the following environment variables.
A locale LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then Brazilian Portuguese is used for the LC_MESSAGES locale. The C locale is used if none of these environment variables are set, or if the locale catalog is not installed, or if grep was not compiled with national language support (NLS).
GREP_OPTIONS This variable specifies default options to be placed in front of any explicit options. For example, if GREP_OPTIONS is '--binary-files=without-match --directories=skip', grep behaves as if the two options --binary-files=without-match and --directories=skip had been specified before any explicit options. Option specifications are separated by whitespace. A backslash escapes the next character, so it can be used to specify an option containing whitespace or a backslash. GREP_COLOR Specifies the marker for highlighting. LC_ALL, LC_COLLATE, LANG These variables specify the LC_COLLATE locale, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the LC_CTYPE locale, which determines the type of characters, e.g., which characters are whitespace. LC_ALL, LC_MESSAGES, LANG These variables specify the LC_MESSAGES locale, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX.2 requires; otherwise, grep behaves more like other GNU programs. POSIX.2 requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX.2 requires that unrecognized options be diagnosed as ``illegal'', but since they are not really against the law the default is to diagnose them as ``invalid''. POSIXLY_CORRECT also disables _N_GNU_nonoption_argv_flags_, described below. _N_GNU_nonoption_argv_flags_ (Here N is grep's numeric process ID.) If the ith character of this environment variable's value is 1, do not consider the ith operand of grep to be an option, even if it appears to be one. A shell can put this variable in the environment for each command it runs, specifying which operands are the results of file name wildcard expansion and therefore should not be treated as options. This behavior is available only with the GNU C library, and only when POSIXLY_CORRECT is not set.【責任編輯:
韓亞珊TEL:(010)68476606】