LoginSignup
27
31

More than 3 years have passed since last update.

grepの利用技まとめ

Last updated at Posted at 2016-01-16

オプション

検索関連

オプション 説明
-r 再帰的にgrepコマンドを実行する
--include=*.rb 指定ファイルのみ検索
--exclude-dir=test 指定フォルダを除外
-w 単語としてマッチする場合(IDEのwhole words only)
-e 検索パターン 検索パターンを指定
-G 基本正規表現を使う
-E 拡張正規表現を使う
-P Perl正規表現を使う
-i 大文字小文字区別しない
-w Matches only word/words instead of substring.
-v マッチしない形を検索結果になる
-n 行番号を表示する

表示関連

オプション 説明
-A number マッチ結果の後ろの何行を表示(after)
-B number マッチ結果の前の何行を表示(before)
-number マッチ結果の前後何行を表示(before and after)
-n 行番号を出力する
-l ファイル一覧を出力する
--color 結果に色つける
--line-buffered bufferしないで出力、ログリアルタイム監視など使う
-s ファイルがない時でエラーが出力されないようにする
-o Display only matched pattern instead of whole line.

検索

複数パターン検索

注意するのは、"|" ではなく "\|"を利用すること

$ grep "aaa\|bbb" test.txt

カレントフォルダ(サブフォルダ含む)で特定の文字含むファイル一覧

grep -rnw ./ -e "pattern"

アクセスログをリアルタイムに表示する

$ tail -f access_log | grep --line-buffered 'test'

grep -vの活用

-vはマッチしない形を結果になる、SQLのNOTのようなもの

grep で#で始まるコメント行および空白行を削除する
$ grep -v -e '^\s*#' -e '^\s*$' filename
プロセス名で検索し、grepを邪魔しないようにする
$ ps aux | grep java | grep -v grep

特定のファイルの文字列のみ検索

_smart_phoneのviewファイルのみ文字列を検索する

find app/views/users2016/ -name "*_smart_phone*" | xargs grep 'content_for :title'

結果を見やすく

aliasで登録する

alias grep="grep --with-filename --line-number --color=always"

-C5で前後5行表示、ログ調査時によく使う

$ grep -C5 'error' log/xxxxx.log

その他

圧縮ファイル解凍せず検索するzgrep

$ zgrep 'test' file_name

マッチした部分のみ表示する

$ zgrep -ro --color 'rand=' sitemaps/

xmlタグの中身を取得

grep -Eo '<tag>(.*?)<\/tag>' test.xml

参考資料

grepコマンドで覚えておきたい使い方14個(+3個)

27
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
31