初めに
ログ調査の際はgrepコマンドを使ってファイル検索を行っているのですが、普段はオプションなどあまり使用せず、使う際も毎回検索して調べてました。この際覚えようと思い調べたので、アウトプットします。
grepコマンドとは
grepコマンドは、ファイル内の文字列を検索するコマンドです。
検索したい文字列と検索対象のファイルを指定することで、簡単に結果を出力することができます。
$ grep test test.txt
test1 111
test2 222
test3 333
test4 444
test5 555
便利なオプション
オプション | 引数 | 説明 |
---|---|---|
-e | 検索する文字 | 検索する文字列を指定。複数個指定することでor検索が可能。 |
-v | - | 検索文字列を含まない行のみ出力 |
-c | - | 検索にマッチした行数を出力 |
-i | - | 大文字と小文字を区別しない |
-C | 行数 | マッチした行の前後の行も表示。引数で指定した行数分表示する。 |
-n | - | 検索結果に何行目かを表示する |
-m | 回数 | 指定回数マッチしたものが見つかったら処理を終了 |
-q | - | 結果を標準出力しない |
-r | - | 検索対象にディレクトリを指定した場合、サブディレクトリのファイルも検索 |
-R | - | 検索対象にディレクトリを指定した場合、サブディレクトリのファイル(シンボリックリンクも含む)も検索 |
使用例
今回のディレクトリ構成は以下です。
./
├ test.txt
└ sub/
└ test2.txt
今回grepに使用するテキストファイルは以下です。
$ cat test.txt
test1 111
test2 222
test3 333
test4 444
test5 555
$
$ cat sub/test2.txt
test6 666
test7 77
使用例1:-eでOR検索
-eを複数用いることでOR検索をすることができます。
$ grep -e test1 -e test2 test.txt
test1 111
test2 222
使用例2:|でand検索
and検索の場合はバーティカルバーを用いて行います。
$ grep -e test test.txt
test1 111
test2 222
test3 333
test4 444
test5 555
$
$ grep -e test test.txt | grep -e 111
test1 111
使用例3:-vでNOT検索
-vで検索文字以外を出力できます。
$ grep -v -e 222 test.txt
test1 111
test3 333
test4 444
test5 555
使用例4:-cで行数のみ出力
-cで行数のみ出力することができます。
$ grep -c -e test test.txt
5
使用例5:-iで大文字と小文字を区別しないで検索
デフォルトの場合大文字と小文字を区別しますが、-iで大文字と小文字を区別しないで検索することができます。
$ grep -c -e TEST test.txt
0
$ grep -c -i -e TEST test.txt
5
使用例6:-Cで前後の行も表示
-Cで検索結果の上下数行を出力することができます。
$ grep -C 1 -e 333 test.txt
test2 222
test3 333
test4 444
ちなみに、-Aと-Bで前後どちらかのみを指定可能です。
$ grep -A 1 -e 333 test.txt
test3 333
test4 444
$ grep -B 1 -e 333 test.txt
test2 222
test3 333
使用例7:-nで何行目かを表示
-nで検索結果の行数を表示することができます。
$ grep -n -e 333 test.txt
3:test3 333
使用例8:-qで結果を標準出力しない
-qで標準出力に表示しないことができます。
一見使い道がないように思えますが、シェルスクリプトのif分岐など、出力の必要がない場合に使用できます。
$ grep -e test test.txt
test1 111
test2 222
test3 333
test4 444
test5 555
$ grep -q -e test test.txt
$
使用例9:-rでサブディレクトリも検索
検索対象にフォルダを指定した場合、-rでサブディレクトリのファイルまで検索対象にすることができます。
$ grep -r -e test ./
./test.txt:test1 111
./test.txt:test2 222
./test.txt:test3 333
./test.txt:test4 444
./test.txt:test5 555
./sub/test2.txt:test6 666
./sub/test2.txt:test7 777
終わりに
grepはオプションをつけることでさらに便利に利用することができます。
毎回調べることなく使えると便利そうなので、たくさん使って手になじませていきたいです。
ここまでご覧いただきありがとうございました!
参考