LoginSignup
1
2

More than 3 years have passed since last update.

【Linux】grepの便利なオプション

Last updated at Posted at 2018-11-30

便利なオプション

たまに使うやつは毎回忘れてググるのでメモ。
※grep対象のパターン指定は"pattern"でも'pattern'でもどっちでもOK

指定した単語を除く

-vの後ろに除きたい単語を指定する

$ grep "https://xxx.co.jp/" /var/log/debug.log | grep -v "200"

大文字と小文字を区別しない

-iのオプションを付けると大文字小文字を区別しない

$ grep -i "retry" /var/log/debug.log

マッチした前後の行も表示

  • 後ろだけ表示したい場合はAfter:-A
  • 前だけ表示したい場合はBefore:-B
  • 前後両方表示したい場合はContext:-C
# 後ろ5行だけ表示したい場合
$ grep -A 5 "retry" /var/log/debug.log

# 前5行だけ表示したい場合
$ grep -B 5 "retry" /var/log/debug.log

# 前5行、後ろ10行を表示したい場合
$ grep -B 5 -A 10 "retry" /var/log/debug.log

# 前後5行を表示したい場合
$ grep -C 5 "retry" /var/log/debug.log

完全一致した単語だけ

-wを付けないとRESPONSE-BODYも引っかかるけど、-wを付けるとRESPONSEと独立してて完全一致する場合だけ引っかかる

$ grep -w "RESPONSE" /var/log/debug.log

複数の単語で検索

複数の単語でOR検索

-eを複数付けて指定するか、-E|を組み合わせて複数の単語を指定するとOR検索になる

$ grep -e "success" -e "count" /var/log/debug.log
$ grep -E "success|count" /var/log/debug.log

複数の単語でAND検索

grepを|でつなげればAND検索になる

$ grep "success" /var/log/debug.log | grep "count"
1
2
2

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
1
2