サーバエンジニアの知恵袋 - grep
GNU grep には様々なオプションがあるが、以下に便利だと思われるオプションの例を挙げる。
GNU grep の詳細は以下のページを参照のこと。
http://www.gnu.org/software/grep/doc/grep.html#SEC...

以下のようなファイルを例にする。

$ cat aaa.txt
abcdefg
hijklmn
opqrstu
vwzyz
test
12345
67890
ABCDEFG
HIJKLMN
OPQRSTU
VWZYZ
abctestdef
123testxyz
aiueo
kakikukeko
sashisuseso
irohanihoheto

まずは基本的なところから。
一致したパターンを含む行の出力

$ grep abc aaa.txt
abcdefg
abctestdef
一致したパターンを含む行を行番号付きで出力

$ grep -n abc aaa.txt
1:abcdefg
12:abctestdef
一致したパターン(大文字と小文字を区別しない)を含む行を出力

$ grep -i abc aaa.txt
abcdefg
ABCDEFG
abctestdef
一致したパターンを含まない行の出力

$ grep -v abc aaa.txt
hijklmn
opqrstu
vwzyz
test
12345
67890
ABCDEFG
HIJKLMN
OPQRSTU
VWZYZ
123testxyz
aiueo
kakikukeko
sashisuseso
irohanihoheto
一致したパターンを含む行の数を出力

$ grep -c abc aaa.txt
2
パターンに一致した行を含むファイル名を出力

$ grep -l abc *
aaa.txt
一致したパターンを含む行を出力(ファイル名を出力しない)

$ grep -h abc *
abcdefg
abctestdef
一致したパターンを含む行を出力(ファイル名を出力する)

$ grep -H abc aaa.txt
aaa.txt:abcdefg
aaa.txt:abctestdef
完全に一致した行だけを出力

$ grep -x abc aaa.txt

$ grep -x abcdefg aaa.txt
abcdefg
標準出力に何も出力しない
パターンに一致したときは、終了ステータスが0。一致しないときは、1になる。

$ grep -q abc aaa.txt

$ echo $?
0

$ grep -q ZZZ aaa.txt

$ echo $?
1
指定した行数だけ、パターンに一致した行の後の行も表示

$ grep -A 2 ABC aaa.txt
ABCDEFG
HIJKLMN
OPQRSTU
指定した行数だけ、パターンに一致した行の前の行も表示

$ grep -B 2 ABC aaa.txt
12345
67890
ABCDEFG
指定した行数(デフォルトは2)だけ、パターンに一致した行の前後の行も表示

$ grep -C 1 ABC aaa.txt
67890
ABCDEFG
HIJKLMN

複数の検索パターンを指定する場合は以下のようにする。
複数のパターンに一致した行を出力(AND)

$ grep abc aaa.txt | grep ef
abcdefg
abctestdef
複数のパターンに一致した行を出力(OR)

$ grep -e 123 -e abc aaa.txt
abcdefg
12345
abctestdef
123testxyz

もしくは次のようにegrepを使う。

$ egrep "123|abc" aaa.txt
abcdefg
12345
abctestdef
123testxyz

以下は色々な正規表現を使った例。
数字を含む行を表示

$ grep '[0123456789]' aaa.txt
12345
67890
123testxyz

もしくは、

$ grep '[0-9]' aaa.txt
12345
67890
123testxyz

あるいは、

$ grep '[[:digit:]]' aaa.txt
12345
67890
123testxyz
数字以外の文字に一致する行を表示

$ grep '[^0-9]' aaa.txt
abcdefg
hijklmn
opqrstu
vwzyz
test
ABCDEFG
HIJKLMN
OPQRSTU
VWZYZ
abctestdef
123testxyz
aiueo
kakikukeko
sashisuseso
irohanihoheto
ピリオド(.)(任意の1文字)を使用した例

$ grep 'te.t' aaa.txt
test
abctestdef
123testxyz

$ grep 'A.*G' aaa.txt
ABCDEFG
行頭に「test」という文字列がある行を表示

$ grep '^test' aaa.txt
test
行末に「Z」という文字のある行を表示

$ grep 'Z$' aaa.txt
VWZYZ

GNU grep の help を表示する

$ grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -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             print version information and exit
      --help                display this help and exit
      --mmap                use memory-mapped input if possible

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 filename for each match
  -h, --no-filename         suppress the prefixing filename on output
      --label=LABEL         print LABEL as filename for standard input
  -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, -r, --recursive       equivalent to --directories=recurse
      --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
      --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)
  -u, --unix-byte-offsets   report offsets as if CRs were not there (MSDOS)

`egrep' means `grep -E'.  `fgrep' means `grep -F'.
Direct invocation as either `egrep' or `fgrep' is deprecated.
With no FILE, or when FILE is -, read standard input.  If less than two FILEs
are given, assume -h.  Exit status is 0 if any line was selected, 1 otherwise;
if any error occurs and -q was not given, the exit status is 2.

Report bugs to <bug-grep@gnu.org>.