膨大なログや走っているプロセスの中から必要な箇所を抽出するために毎日のようにお世話になっているgrepですが、その機能は樹海のように深い。ここでgrepの基本を抑えてエンジニアとしてのスタートラインに立とう!
オプション一覧
-i | 大文字と小文字を区別せず検索する |
-E | 拡張正規表現で検索をする |
-e | 一致処理に指定した正規表現で検索する |
-v | 一致しないものを検索する |
-n | 検索結果に行番号を表示する |
-c | 一致するものが含まれている回数のみ表示する |
-l | 検索結果にファイル名のみ表示する |
-h | 検索結果にファイル名を表示しない |
-H | 検索結果にファイル名を表示する(ファイルが1つしかない場合でも) |
-o | 検索結果に一致した文字を表示する |
-C 行数,-行数 | 検索結果に一致した箇所から前後に指定した行数を表示する |
-A 行数 | 検索結果に一致した箇所から指定した行数分あとの行を表示する |
-B 行数 | 検索結果に一致した箇所から指定した行数分前の行を表示する |
-r | ディレクトリ内も検索対象とする |
-L | 検索した結果、該当しなかったファイルを表示する |
grep基本的な使い方
$ grep 検索正規表現 <ファイル名>
$ cat <ファイル名> | grep 検索正規表現
カレントディレクトリにある複数のファイルから文字列”apple”を検索する
$ ls #2つのファイルを用意
sample1.txt sample2.txt
$ cat sample1.txt #テキストの中を確認
1000 apple
1000 banana
2000 alchole
$ cat sample2.txt #テキストの中を確認
100 apple
200 orange
300 banana
$ grep 'apple' ./* #カレントディレクトリのファイルから'apple'を検索
./sample1.txt:1000 apple
./sample2.txt:100 apple
$ grep -c 'apple' ./* #カレントディレクトリのファイルから'apple'の検索箇所のカウント数を表示する
./sample1.txt:1
./sample2.txt:1
$ grep -v 'apple' ./* #カレントディレクトリのファイルから'apple'を含まない行を表示する
./sample1.txt:1000 banana
./sample1.txt:2000 alchole
./sample1.txt:
./sample2.txt:200 orange
./sample2.txt:300 banana
$ grep -A 1 'apple' ./* #カレントディレクトリのファイルから'apple'を含む行と、1行後の行を表示する
./sample1.txt:1000 apple
./sample1.txt-1000 banana
--
./sample2.txt:100 apple
./sample2.txt-200 orange
grepでAND(かつ)検索
$ grep 検索正規表現1 <ファイル名> | grep 検索正規表現2
$ cat <ファイル名> | grep 検索正規表現1 | grep 検索正規表現2
パイプ「|」でつないでAND検索をする
$ grep 'apple' ./* | grep '100' #カレントディレクトリのファイルから'apple'かつ'100'を含む行を表示する
./sample1.txt:1000 apple
./sample2.txt:100 apple
$ grep 'apple' ./* | grep '1000' #カレントディレクトリのファイルから'apple'かつ'1000'を含む行を表示する
./sample1.txt:1000 apple
grepでOR(または)検索
$ grep -e 検索正規表現1 -e 検索正規表現2 <ファイル名>
$ cat <ファイル名> | grep -e 検索正規表現1 -e 検索正規表現2
$ grep -e 'apple' -e '1000' ./* #カレントディレクトリのファイルから'apple' OR '1000'を検索
./sample1.txt:1000 apple
./sample1.txt:1000 banana
./sample2.txt:100 apple
$ cat ./* | grep -e 'apple' -e '1000' #カレントディレクトリのファイルから'apple' OR '1000'を検索
1000 apple
1000 banana
100 apple
grep正規表現検索
$ grep ‘^行先頭文字列’ <ファイル名>
$ grep ‘行末尾文字列$’ <ファイル名>
$ grep ‘文字列*’ <ファイル名>
$ grep ‘.文字列’ <ファイル名>
行先頭文字列を指定したり、行末尾文字列を指定したり、便利な使い方をご紹介します。
$ grep '^10' ./* #行の先頭が「10」で始まる行を検索する
./sample1.txt:1000 apple
./sample1.txt:1000 banana
./sample2.txt:100 apple
$ grep 'na$' ./* #行の末尾が「na」で終わる行を検索する
./sample1.txt:1000 banana
./sample2.txt:300 banana
$ grep 'app*' ./* #「app」を含む任意の文字列を検索
./sample1.txt:1000 apple
./sample2.txt:100 apple
$ grep '.000' ./* #「000」の前に任意の1文字を含む文字列を検索
./sample1.txt:1000 apple
./sample1.txt:1000 banana
./sample1.txt:2000 alchole
-Eオプション
拡張正規表現を使った例をご紹介します。
$ grep -E 'apple|orange' ./* #「apple」OR(または)「orange」を検索
./sample1.txt:1000 apple
./sample2.txt:100 apple
./sample2.txt:200 orange
$ grep -E [0-9]{4} ./* #0〜9の任意の数字が4回繰り返している文字列を検索
./sample1.txt:1000 apple
./sample1.txt:1000 banana
./sample1.txt:2000 alchole
便利だわ。。。
コメント