使用法: egrep [OPTION]... PATTERN [FILE]...
各 FILE または標準入力内の PATTERN を検索します。
PATTERN はデフォルトでは基本正規表現 (BRE) です。
例: egrep -i 'hello world' menu.h main.c
正規表現の選択および解釈:
-E, --extended-regexp PATTERN を拡張正規表現 (ERE) とする
-F, --fixed-strings PATTERN を改行で区切られた固定文字列の組とする
-G, --basic-regexp PATTERN を基本正規表現 (BRE) とする
-P, --perl-regexp PATTERN を Perl 正規表現とする
-e, --regexp=PATTERN 一致処理に PATTERN を使用する
-f, --file=FILE FILE から PATTERN を取得する
-i, --ignore-case 大文字と小文字を区別しない
-w, --word-regexp 強制的に単語全体で PATTERN の一致処理を行う
-x, --line-regexp 強制的に行全体で PATTERN の一致処理を行う
-z, --null-data データの行末を改行ではなく NULL とする
Miscellaneous:
-s, --no-messages suppress error messages
-v, --invert-match select non-matching lines
-V, --version display version information and exit
--help display this help text and exit
出力の制御:
-m, --max-count=NUM NUM 回一致後に中断する
-b, --byte-offset 出力行と併せてバイトオフセットを表示する
-n, --line-number 出力行と併せて行番号を表示する
--line-buffered 行ごとに出力を flush する
-H, --with-filename 一致するごとにファイル名を表示する
-h, --no-filename 出力の先頭にファイル名を付けない
--label=LABEL 標準入力のファイル名の接頭辞として LABEL を使用する
-o, --only-matching show only the part of a line matching PATTERN
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume that binary files are TYPE;
TYPE is 'binary', 'text', or 'without-match'
-a, --text equivalent to --binary-files=text
-I equivalent to --binary-files=without-match
-d, --directories=ACTION how to handle directories;
ACTION is 'read', 'recurse', or 'skip'
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
ACTION is 'read' or 'skip'
-r, --recursive like --directories=recurse
-R, --dereference-recursive
likewise, but follow all symlinks
--include=FILE_PATTERN
search only files that match FILE_PATTERN
--exclude=FILE_PATTERN
skip files and directories matching FILE_PATTERN
--exclude-from=FILE skip files matching any file pattern from FILE
--exclude-dir=PATTERN directories that match PATTERN will be skipped.
-L, --files-without-match print only names of FILEs containing no match
-l, --files-with-matches print only names of FILEs containing matches
-c, --count print only a count of matching lines per FILE
-T, --initial-tab make tabs line up (if needed)
-Z, --null print 0 byte after FILE name
前後の表示に関する制御:
-B, --before-context=NUM 一致した前の NUM 行を表示する
-A, --after-context=NUM 一致した後の NUM 行を表示する
-C, --context=NUM 一致した前後 NUM 行を表示する
-NUM same as --context=NUM
--group-separator=SEP use SEP as a group separator
--no-group-separator use empty string as a group separator
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
-u, --unix-byte-offsets report offsets as if CRs were not there
(MSDOS/Windows)
'egrep' means 'grep -E'. 'fgrep' means 'grep -F'.
Direct invocation as either 'egrep' or 'fgrep' is deprecated.
When FILE is -, read standard input. With no FILE, read . if a command-line
-r is given, - otherwise. If fewer than two FILEs are given, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.
バグを発見したら
Usage: egrep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: egrep -i 'hello world' menu.h main.c
Regexp selection and interpretation:
-E, --extended-regexp PATTERN is an extended regular expression (ERE)
-F, --fixed-strings PATTERN is a set of newline-separated fixed strings
-G, --basic-regexp PATTERN is a basic regular expression (BRE)
-P, --perl-regexp PATTERN is a Perl regular expression
-e, --regexp=PATTERN use PATTERN for matching
-f, --file=FILE obtain PATTERN from FILE
-i, --ignore-case ignore case distinctions
-w, --word-regexp force PATTERN to match only whole words
-x, --line-regexp force PATTERN to match only whole lines
-z, --null-data a data line ends in 0 byte, not newline
Miscellaneous:
-s, --no-messages suppress error messages
-v, --invert-match select non-matching lines
-V, --version display version information and exit
--help display this help text and exit
Output control:
-m, --max-count=NUM stop after NUM matches
-b, --byte-offset print the byte offset with output lines
-n, --line-number print line number with output lines
--line-buffered flush output on every line
-H, --with-filename print the file name for each match
-h, --no-filename suppress the file name prefix on output
--label=LABEL use LABEL as the standard input file name prefix
-o, --only-matching show only the part of a line matching PATTERN
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume that binary files are TYPE;
TYPE is 'binary', 'text', or 'without-match'
-a, --text equivalent to --binary-files=text
-I equivalent to --binary-files=without-match
-d, --directories=ACTION how to handle directories;
ACTION is 'read', 'recurse', or 'skip'
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
ACTION is 'read' or 'skip'
-r, --recursive like --directories=recurse
-R, --dereference-recursive
likewise, but follow all symlinks
--include=FILE_PATTERN
search only files that match FILE_PATTERN
--exclude=FILE_PATTERN
skip files and directories matching FILE_PATTERN
--exclude-from=FILE skip files matching any file pattern from FILE
--exclude-dir=PATTERN directories that match PATTERN will be skipped.
-L, --files-without-match print only names of FILEs containing no match
-l, --files-with-matches print only names of FILEs containing matches
-c, --count print only a count of matching lines per FILE
-T, --initial-tab make tabs line up (if needed)
-Z, --null print 0 byte after FILE name
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
--group-separator=SEP use SEP as a group separator
--no-group-separator use empty string as a group separator
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
-u, --unix-byte-offsets report offsets as if CRs were not there
(MSDOS/Windows)
'egrep' means 'grep -E'. 'fgrep' means 'grep -F'.
Direct invocation as either 'egrep' or 'fgrep' is deprecated.
When FILE is -, read standard input. With no FILE, read . if a command-line
-r is given, - otherwise. If fewer than two FILEs are given, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.
Report bugs to: bug-grep@gnu.org
GNU Grep home page:
GREP(1) GREP(1) 名称 grep, egrep, fgrep, zgrep - パターンにマッチする行を表示する 書式 grep [options] PATTERN [FILE...] grep [options] [-e PATTERN | -f FILE] [FILE...] 解説 grep は、 FILE で名前を指定された入力ファイル (ファイルが指定されてない か、 file の部分に - が指定された場合は標準入力) を読み込み、与えられた PATTERN にマッチする部分を含む行を探します。デフォルト動作では、 grep はマッチした行を表示します。 さらに、2 つのプログラム egrep と fgrep を利用可能 で す 。 egrep は grep -E と同じです。 fgrep は grep -F と同じです。 zgrep は grep -Z と 同じです。 オプション -A NUM, --after-context=NUM NUM で指定した行数だけ、パターンにマッチした行の後の行も表示しま す。 -a, --text バイナリファイルをテキストファイルであるかのように処理します。こ れは --binary-files=text オプションと等価です。 -B NUM, --before-context=NUM NUM で指定した行数だけ、パターンにマッチした行の前の行も表示しま す。 -C [NUM], -NUM, --context[=NUM] NUM で指定した行数 (デフォルトは 2) だけ、パターンにマッチした行 の前後の行も表示します。 -b, --byte-offset 各出力行の前に、入力ファイルの先頭からのバイト単位のオフセットを 表示します。 --binary-files=TYPE ファイルの最初の数バイトが、ファイルの内容がバイナリファイルであ ることを示す場合、ファイルのタイプを TYPE であると仮定します。デ フォルトでは TYPE は binary であり、 grep は通常、バイナリファイ ルの一致を示す一行メッセージを表示するか、マッチしない場合にはな に も表示しません。 TYPE が without-match の場合、 grep はバイナ リファイルはマッチしないものと仮定します。これは -I オプションと 等価です。 TYPE が text の場合、 grep はバイナリファイルをテキス トであるかのように扱います。これは -a オプションと等価です。 警 告: grep --binary-files=text はバイナリのゴミを表示する可能性が あります。出力先が端末である場合で、端末ドライバがこのゴミの一部 をコマンドであると解釈する場合、このゴミが悪い副作用をおよぼす可 能性があります。 -c, --count 通常の出力はせず、各入力ファイルについてマッチした行数を表示しま す。 -v, --invert-match オプションと共に指定した場合は、マッチし なかった行数を表示します (下記参照)。 -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 を改行で区切られた固定文字列のリストとして扱います。その 文字列のどれかとマッチするかを調べます。 -f FILE, --file=FILE パ ターンを FILE から 1 行ごとに読み込みます。空のファイルはパタ ーンを含まないので、何にもマッチしません。 -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 通常の出力はせず、このオプションを指定しなかったときに出力される 入力ファイルの名前を表示します。スキャン動作は最初のマッチで終了 します。 --mmap 可能ならば、デフォルトの read(2) システムコ ー ル の 代 わ り に mmap(2) システムコールを使って入力を読み取ります。ある状況におい て、 --mmap はよりよい性能をもたらします。しかし、 grep の動作中 に 入力ファイルが小さくなるか、または I/O エラーが生じた場合に、 --mmap は (コアダンプを含む) 未定義の動作を引き起こす可能性が あ ります。 -n, --line-number 各出力行の前に、入力ファイルにおける行番号を表示します。 -q, --quiet, --silent 沈黙。通常の出力を抑止します。スキャン動作は最初のマッチで終了し ます。下記の -s や --no-messages オプションも参照。 -r, --recursive 各ディレクトリ下のすべてのファイルを再帰的に読み取ります。これは -d recurse オプションと等価です。 -s, --no-messages 指定されたファイルが存在しないことや読み込みできないことを示すエ ラーメッセージを抑止します。移植性に関する注: GNU grep とは異 な り 、伝統的な grep は POSIX.2 に適合していませんでした。なぜなら 、伝統的な grep には -q オプションが無く、 -s オプション は GNU grep の -q オプションの様に動作したからです。伝統的な grep へ移 植可能であることを意図したシェルスクリプトは、 -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 文字が取り除かれたファイルであるかのごとくにバイト単位オフ セットを報告します。このことは grep を Unix マシンで動作させたの と同じ結果を生成します。このオプションは -b オプションも使用しな い限り効果がありません。 MS-DOS と MS-Windows 以外のプラットフォ ームでは効果がありません。 -V, --version grep のバージョン番号を標準エラー出力に表示します。バグレポー ト には、この番号を付記してください (下記参照)。 -v, --invert-match 結果を反転し、マッチしなかった行を選択します。 -w, --word-regexp 完全な語にマッチする行のみを選択します。マッチする部分文字列が行 頭から始まっているか、単語構成文字以外の文字が前にあることがテス トされます。同様に、マッチする部分文字列が行末まであるか、単語構 成文字以外の文字が後にある必要があります。単語構成文字とは、レタ ー・数字・アンダスコアです。 -x, --line-regexp 行全体と正確にマッチする行のみを選択します。 -y -i と同じ意味を持つ旧式のオプションです。 --null 通常ファイル名の後に続く文字の代わりにバイト 0 (ASCII NUL 文字) を出力します。例えば、 grep -l --null は各ファイル名の後に、通常 の newline ではなくバイト 0 を出力します。このオプションを指定す ると、 newline 等の例外的な文字を含むファイル名に直面した場合 で も 出力が明白になります。このオプションを find -print0, perl -0, sort -z, xargs -0 等のコマンドと共に使用すれば、任意のファイル名 を 処理できます。ファイル名が newline 文字を含んでいても処理可能 です。 -Z, --decompress 検索を開始する前に入力データを伸長します。このオプションは zlib ライブラリと共にコンパイルした場合のみ使用可能です。 正規表現 正 規表現は、文字列の集合を表現するパターンの事です。数式表現と同様に、 より小さな表現を組み合わせるさまざまな演算子を用いる事で、正規表現を 組 み立てます。 grep は、「基本」正規表現と「拡張」正規表現の 2 種類の正規表現文法を扱 う事ができます。 GNU grep では、どちらの正規表現文法も機能的な違いは あ り ません。他の実装では、基本正規表現は拡張正規表現より能力が低くなって います。ここでは、拡張正規表現について説明します。基本正規表現との違 い は、その後に説明します。 正 規表現の基本単位は、1 文字にマッチする正規表現です。レターと数字を含 む多くの文字は、それ自身にマッチする正規表現です。また、特殊な意味を 持 つ メタ文字も、その文字の前にバックスラッシュを付けると、その本来の文字 にマッチするようになります。 [ と ] で囲まれた文字のリストは、そのリスト中に含まれるどれか 1 文字 に マッチします。ただし、リストの先頭がキャレット ^ の場合は、そのリストに 含まれ ない文字にマッチします。例えば、正規表現 [0123456789] は数 字 1 文字にマッチします。文字の範囲は最初と最後の文字をハイフン (‘-’) でつな ぐことで指定できます。最後に、特定の名前を持つ文字クラスがあらかじめ 定 義 さ れ て い ま す 。 名 前 が内容を示しており、それらは、 [:alnum:], [:alpha:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], [:xdigit:] です。例えば、 [[:alnum:]] は [0-9A-Za-z] と同じですが、後者は POSIX ロケールや ASCII コード順に依 存 しますので、前者の方がロケールや文字集合に依存しません。 (クラス名の 中の角括弧はシンボル名の一部であり、リストを区切る角括弧とは別に指定 す る 必要があることに注意) リストの中では、ほとんどのメタ文字は通常の文字 として扱われます。リテラル ] を含めるには、この文字をリストの先頭に置い てください。同様に、リテラル ^ を含めるには、この文字をリストの先頭以外 に置いてください。リテラル - を含めるには、この文字をリストの最後に置い てください。 ピリオド . は、任意の 1 文字にマッチします。シンボル \w は [[:alnum:]] と同じ意味で、シンボル \W は [^[:alnum:]] と同じ意味です。 キャレット ^ と、ドル記号 $ は、それぞれ行頭と行末の空文字列にマッチ す る メタ文字です。シンボル \< とシンボル \> は、それぞれ単語の先頭と末尾 の空文字列にマッチするメタ文字です。シンボル \b は単語の端の空文字列 に マッチします。シンボル \B は単語の端 以外の空文字列にマッチします。 正規表現の後には、繰り返し演算子のどれかが続くことがあります。 ? 直前の項目はオプションであり、最大 1 回マッチします。 * 直前の項目は 0 回以上マッチします。 + 直前の項目は 1 回以上マッチします。 {n} 直前の項目は厳密に n 回マッチします。 {n,} 直前の項目は n 回以上マッチします。 {n,m} 直前の項目は、最低 n 回、最大 m 回マッチします。 2 つの正規表現は結合可能です。結果としてできあがる正規表現は、結合され た 2 つの部分表現にそれぞれマッチする 2 つの部分文字列を結合した任意 の 文字列にマッチします。 2 つの正規表現は中置き型演算子 | で繋ぐことが可能です。結果としてできあ がる正規表現は、どちらかの部分表現にマッチする任意の文字列にマッチし ま す。 繰 り返しは結合に優先します。また結合は選択に優先します。これらの優先規 則を無効とするために、部分表現全体を括弧で囲むことが可能です。 n が 1 つの数字であるような後方参照 \n は、正規表現中の括弧で囲まれた n 番目の部分表現がマッチした文字列とマッチします。 基 本正規表現では、メタ文字 ?, +, {, |, (, ) は、その特殊な意味を失いま す。代わりに、バックスラッシュを付けた \?, \+, \{, \|, \(, \) を使用 し てください。 伝 統的な egrep は、メタ文字 { をサポートしませんでした。また、このメタ 文字の代わりに \{ をサポートする egrep 実装もいくつか存在するので、移植 可 能なスクリプトでは、リテラル { にマッチさせるために egrep パターンで { を使うことは避けて [{] を使うべきです。 GNU egrep は、 { が不正な範囲指定の始まりであるなら特殊文字ではない、と 想 定 し て、伝統的な使用法のサポートを試みます。例えば、シェルコマンド egrep ’{1’ は正規表現の文法エラーを報告せずに、2 文字の文字列 {1 を検索 します。 POSIX.2 は、この動作を一つの拡張として許可していますが、移植可 能なスクリプトではこの使用法を避けるべきです。 環境変数 GREP_OPTIONS この変数は明示的なオプションの前に指定されるデフォルトオプション を指定します。例えば、もし GREP_OPTIONS が ’--binary-files=with- out-match --directories=skip’ である場合、 grep は 2 つのオプ シ ョン --binary-files=without-match と --directories=skip が明示的 なオプションの前に指定されている様に動作します。オプションの指定 は空白によって区切られます。バックスラッシュは次の文字をエスケー プします。これは空白やバックスラッシュを含むオプションを指定する ために用いられます。 LC_ALL, LC_MESSAGES, LANG これらの変数は grep がメッセージに使用する言語を決定する LC_MES- SAGES を指定します。ロケールはこれらの変数のうち最初に設定されて いるものにより決定されます。もしこれらの変数全てが設定されていな い場合、またはメッセージカタログがインストールされていない場合、 ま たは grep が国際言語サポートつき (NLS) でコンパイルされてない 場合には、アメリカンイングリッシュが用いられます。 LC_ALL, LC_CTYPE, LANG これらの変数は、例えばどの文字が空白であるかなど、文字の種類を決 定する LC_CTYPE を指定します。ロケールはこれらの変数のうち最初に 設定されているものにより決定されます。もしこれらの変数全てが設定 されていない場合、またはメッセージカタログがインストールされてい ない場合、または grep が国際言語サポートつき (NLS) でコンパイ ル されてない場合には、 POSIX ロケールが用いられます。 POSIXLY_CORRECT 設 定されている場合、 grep は POSIX.2 として動作し、それ以外の場 合は grep は他の GNU プログラムのように動作します。 POSIX.2 では ファイル名の後に続くオプションはファイル名として扱われます。デフ ォルトでは、このようなオプションはオペランドリストの先頭に並び変 えられて、オプションとして扱われます。また、POSIX.2 では認識でき ないオプションは “ 不法 (illegal)” であると診断されますが、法 律 に 違 反 し て いるわけではないので、デフォルトではこれらは“不正 (invalid)” であると診断されます。 診断 通常、パターンにマッチした行が見つかった場合は 0 を、見つからなかった場 合 は 1 を返します。(ただし、 -v オプションを指定した場合は、逆になりま す。) パターンに文法エラーが存在したり、入力ファイルにアクセスできな い などのシステムエラーが発生した場合は、2 を返します。 バグ バ グレポートは、 bug-gnu-utils@gnu.org まで Email してください。この時 、“Subject:” のどこかに “grep” という単語を忘れずに入れてください。 {m,n} の表現で非常に大きな繰り返しを指定すると、非常に多くのメモリを 消 費 します。さらに、ある種のあいまいな正規表現を指定すると、必要となる時 間とメモリ領域は指数的に増大し、 grep がメモリ不足を起こす可能性があ り ます。 後方参照は非常に動作が遅く、必要となる時間は指数的に増大します。 GNU Project 2000/06/09 GREP(1)
GREP(1) GREP(1)
NAME
grep, egrep, fgrep - print lines matching a pattern
SYNOPSIS
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
DESCRIPTION
grep searches the named input FILEs (or standard input if no files are
named, or if a single hyphen-minus (-) is given as file name) 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. Direct
invocation as either egrep or fgrep is deprecated, but is provided to
allow historical applications that rely on them to run unmodified.
OPTIONS
Generic Program Information
--help Print a usage message briefly summarizing these command-line
options and the bug-reporting address, then exit.
-V, --version
Print the version number of grep to the standard output stream.
This version number should be included in all bug reports (see
below).
Matcher Selection
-E, --extended-regexp
Interpret PATTERN as an extended regular expression (ERE, see
below). (-E is specified by POSIX.)
-F, --fixed-strings, --fixed-regexp
Interpret PATTERN as a list of fixed strings, separated by
newlines, any of which is to be matched. (-F is specified by
POSIX, --fixed-regexp is an obsoleted alias, please do not use
it new scripts.)
-G, --basic-regexp
Interpret PATTERN as a basic regular expression (BRE, see
below). This is the default.
-P, --perl-regexp
Interpret PATTERN as a Perl regular expression. This is highly
experimental and grep -P may warn of unimplemented features.
Matching Control
-e PATTERN, --regexp=PATTERN
Use PATTERN as the pattern. This can be used to specify
multiple search patterns, or to protect a pattern beginning with
a hyphen (-). (-e is specified by POSIX.)
-f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file
contains zero patterns, and therefore matches nothing. (-f is
specified by POSIX.)
-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input
files. (-i is specified by POSIX.)
-v, --invert-match
Invert the sense of matching, to select non-matching lines. (-v
is specified by POSIX.)
-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.
(-x is specified by POSIX.)
-y Obsolete synonym for -i.
General Output Control
-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. (-c is specified by POSIX.)
--color[=WHEN], --colour[=WHEN]
Surround the matched (non-empty) strings, matching lines,
context lines, file names, line numbers, byte offsets, and
separators (for fields and groups of context lines) with escape
sequences to display them in color on the terminal. The colors
are defined by the environment variable GREP_COLORS. The
deprecated environment variable GREP_COLOR is still supported,
but its setting does not have priority. WHEN is never, always,
or auto.
-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. (-l is specified by
POSIX.)
-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.
-o, --only-matching
Print only the matched (non-empty) parts of a matching line,
with each such part on a separate output line.
-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.
(-q is specified by POSIX.)
-s, --no-messages
Suppress error messages about nonexistent or unreadable files.
Portability note: unlike GNU grep, 7th Edition Unix grep did not
conform to POSIX, because it lacked -q and its -s option behaved
like GNU grep’s -q option. USG-style grep also lacked -q but
its -s option behaved like GNU grep. Portable shell scripts
should avoid both -q and -s and should redirect standard and
error output to /dev/null instead. (-s is specified by POSIX.)
Output Line Prefix Control
-b, --byte-offset
Print the 0-based byte offset within the input file before each
line of output. If -o (--only-matching) is specified, print the
offset of the matching part itself.
-H, --with-filename
Print the file name for each match. This is the default when
there is more than one file to search.
-h, --no-filename
Suppress the prefixing of file names on output. This is the
default when there is only one file (or only standard input) to
search.
--label=LABEL
Display input actually coming from standard input as input
coming from file LABEL. This is especially useful when
implementing tools like zgrep, e.g., gzip -cd foo.gz | grep
--label=foo -H something. See also the -H option.
-n, --line-number
Prefix each line of output with the 1-based line number within
its input file. (-n is specified by POSIX.)
-T, --initial-tab
Make sure that the first character of actual line content lies
on a tab stop, so that the alignment of tabs looks normal. This
is useful with options that prefix their output to the actual
content: -H,-n, and -b. In order to improve the probability
that lines from a single file will all start at the same column,
this also causes the line number and byte offset (if present) to
be printed in a minimum size field width.
-u, --unix-byte-offsets
Report Unix-style byte offsets. This switch causes grep to
report byte offsets as if the file were a 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.
-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.
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (described under
--group-separator) between contiguous groups of matches. With
the -o or --only-matching option, this has no effect and a
warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under
--group-separator) between contiguous groups of matches. With
the -o or --only-matching option, this has no effect and a
warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a
group separator (described under --group-separator) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen
(--).
--no-group-separator
Use empty string as a group separator.
File and Directory Selection
-a, --text
Process a binary file as if it were text; this is equivalent to
the --binary-files=text option.
--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.
-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, i.e., read directories just as if they
were ordinary files. If ACTION is skip, silently skip
directories. If ACTION is recurse, read all files under each
directory, recursively, following symbolic links only if they
are on the command line. This is equivalent to the -r option.
--exclude=GLOB
Skip files whose base name matches GLOB (using wildcard
matching). A file-name glob can use *, ?, and [...] as
wildcards, and \ to quote a wildcard or backslash character
literally.
--exclude-from=FILE
Skip files whose base name matches any of the file-name globs
read from FILE (using wildcard matching as described under
--exclude).
--exclude-dir=DIR
Exclude directories matching the pattern DIR from recursive
searches.
-I Process a binary file as if it did not contain matching data;
this is equivalent to the --binary-files=without-match option.
--include=GLOB
Search only files whose base name matches GLOB (using wildcard
matching as described under --exclude).
-r, --recursive
Read all files under each directory, recursively, following
symbolic links only if they are on the command line. This is
equivalent to the -d recurse option.
-R, --dereference-recursive
Read all files under each directory, recursively. Follow all
symbolic links, unlike -r.
Other Options
--line-buffered
Use line buffering on output. This can cause a performance
penalty.
-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.
-z, --null-data
Treat the input as a set of lines, each terminated by a zero
byte (the ASCII NUL character) instead of a newline. Like the
-Z or --null option, this option can be used with commands like
sort -z to process arbitrary file names.
REGULAR EXPRESSIONS
A 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 three different versions of regular expression syntax:
“basic,” “extended” and “perl.” In GNU grep, there is no difference in
available functionality between basic and extended syntaxes. 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.
Perl regular expressions give additional functionality, and are
documented in pcresyntax(3) and pcrepattern(3), but may not be
available on every system.
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 meta-character with
special meaning may be quoted by preceding it with a backslash.
The period . matches any single character.
Character Classes and Bracket Expressions
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 the character class of numbers and
letters in the current locale. In the C locale and ASCII character set
encoding, this is the same as [0-9A-Za-z]. (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 expression.) Most
meta-characters lose their special meaning inside bracket expressions.
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.
Anchoring
The caret ^ and the dollar sign $ are meta-characters that respectively
match the empty string at the beginning and end of a line.
The Backslash Character and Special Expressions
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. The symbol \w is a synonym for [_[:alnum:]] and
\W is a synonym for [^_[:alnum:]].
Repetition
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.
{,m} The preceding item is matched at most m times. This is a GNU
extension.
{n,m} The preceding item is matched at least n times, but not more
than m times.
Concatenation
Two regular expressions may be concatenated; the resulting regular
expression matches any string formed by concatenating two substrings
that respectively match the concatenated expressions.
Alternation
Two regular expressions may be joined by the infix operator |; the
resulting regular expression matches any string matching either
alternate expression.
Precedence
Repetition takes precedence over concatenation, which in turn takes
precedence over alternation. A whole expression may be enclosed in
parentheses to override these precedence rules and form a
subexpression.
Back References and Subexpressions
The back-reference \n, where n is a single digit, matches the substring
previously matched by the nth parenthesized subexpression of the
regular expression.
Basic vs Extended Regular Expressions
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 allows this behavior as an extension, but
portable scripts should avoid it.
ENVIRONMENT VARIABLES
The behavior of grep is affected by the following environment
variables.
The locale for category 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 the Brazilian
Portuguese locale is used for the LC_MESSAGES category. The C locale
is used if none of these environment variables are set, 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
This variable specifies the color used to highlight matched
(non-empty) text. It is deprecated in favor of GREP_COLORS, but
still supported. The mt, ms, and mc capabilities of GREP_COLORS
have priority over it. It can only specify the color used to
highlight the matching non-empty text in any matching line (a
selected line when the -v command-line option is omitted, or a
context line when -v is specified). The default is 01;31, which
means a bold red foreground text on the terminal’s default
background.
GREP_COLORS
Specifies the colors and other attributes used to highlight
various parts of the output. Its value is a colon-separated
list of capabilities that defaults to
ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv
and ne boolean capabilities omitted (i.e., false). Supported
capabilities are as follows.
sl= SGR substring for whole selected lines (i.e., matching
lines when the -v command-line option is omitted, or non-
matching lines when -v is specified). If however the
boolean rv capability and the -v command-line option are
both specified, it applies to context matching lines
instead. The default is empty (i.e., the terminal’s
default color pair).
cx= SGR substring for whole context lines (i.e., non-matching
lines when the -v command-line option is omitted, or
matching lines when -v is specified). If however the
boolean rv capability and the -v command-line option are
both specified, it applies to selected non-matching lines
instead. The default is empty (i.e., the terminal’s
default color pair).
rv Boolean value that reverses (swaps) the meanings of the
sl= and cx= capabilities when the -v command-line option
is specified. The default is false (i.e., the capability
is omitted).
mt=01;31
SGR substring for matching non-empty text in any matching
line (i.e., a selected line when the -v command-line
option is omitted, or a context line when -v is
specified). Setting this is equivalent to setting both
ms= and mc= at once to the same value. The default is a
bold red text foreground over the current line
background.
ms=01;31
SGR substring for matching non-empty text in a selected
line. (This is only used when the -v command-line option
is omitted.) The effect of the sl= (or cx= if rv)
capability remains active when this kicks in. The
default is a bold red text foreground over the current
line background.
mc=01;31
SGR substring for matching non-empty text in a context
line. (This is only used when the -v command-line option
is specified.) The effect of the cx= (or sl= if rv)
capability remains active when this kicks in. The
default is a bold red text foreground over the current
line background.
fn=35 SGR substring for file names prefixing any content line.
The default is a magenta text foreground over the
terminal’s default background.
ln=32 SGR substring for line numbers prefixing any content
line. The default is a green text foreground over the
terminal’s default background.
bn=32 SGR substring for byte offsets prefixing any content
line. The default is a green text foreground over the
terminal’s default background.
se=36 SGR substring for separators that are inserted between
selected line fields (:), between context line fields,
(-), and between groups of adjacent lines when nonzero
context is specified (--). The default is a cyan text
foreground over the terminal’s default background.
ne Boolean value that prevents clearing to the end of line
using Erase in Line (EL) to Right (\33[K) each time a
colorized item ends. This is needed on terminals on
which EL is not supported. It is otherwise useful on
terminals for which the back_color_erase (bce) boolean
terminfo capability does not apply, when the chosen
highlight colors do not affect the background, or when EL
is too slow or causes too much flicker. The default is
false (i.e., the capability is omitted).
Note that boolean capabilities have no =... part. They are
omitted (i.e., false) by default and become true when specified.
See the Select Graphic Rendition (SGR) section in the
documentation of the text terminal that is used for permitted
values and their meaning as character attributes. These
substring values are integers in decimal representation and can
be concatenated with semicolons. grep takes care of assembling
the result into a complete SGR sequence (\33[...m). Common
values to concatenate include 1 for bold, 4 for underline, 5 for
blink, 7 for inverse, 39 for default foreground color, 30 to 37
for foreground colors, 90 to 97 for 16-color mode foreground
colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes
foreground colors, 49 for default background color, 40 to 47 for
background colors, 100 to 107 for 16-color mode background
colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes
background colors.
LC_ALL, LC_COLLATE, LANG
These variables specify the locale for the LC_COLLATE category,
which determines the collating sequence used to interpret range
expressions like [a-z].
LC_ALL, LC_CTYPE, LANG
These variables specify the locale for the LC_CTYPE category,
which determines the type of characters, e.g., which characters
are whitespace.
LC_ALL, LC_MESSAGES, LANG
These variables specify the locale for the LC_MESSAGES category,
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 requires; otherwise, grep behaves
more like other GNU programs. POSIX 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 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.
EXIT STATUS
Normally, the exit status is 0 if selected lines are found and 1
otherwise. But the exit status is 2 if an error occurred, unless the
-q or --quiet or --silent option is used and a selected line is found.
Note, however, that POSIX only mandates, for programs such as grep,
cmp, and diff, that the exit status in case of error be greater than 1;
it is therefore advisable, for the sake of portability, to use logic
that tests for this general condition instead of strict equality
with 2.
COPYRIGHT
Copyright 1998-2000, 2002, 2005-2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is
NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
BUGS
Reporting Bugs
Email bug reports to
Copyright(C) linux-cmd.com All Rights Reserved. Author Takayuki Yukawa