LoginSignup
1
2

ログファイルから特定行を抽出する grep -E コマンド

Last updated at Posted at 2023-03-04

膨大なログから必要な情報だけを抽出する作業に手間取ったのでメモ

grep -E コマンドで抽出する

grepコマンドに -E オプションをつけると正規表現による抽出が可能で便利

grep -E "特定の文字列" ファイル名

以下のようなログが記述されているtest.logというファイルがあるとする

2023-02-07 17:00:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:05:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:10:00 WebApp test.log [WARN] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:15:00 WebApp test.log [WARN] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:30:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:35:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...

ここからSampleAppという文字列を含むを行だけ抽出する場合は以下のコマンドを実行

grep -E "SampleApp" test.log

実行結果

2023-02-07 17:00:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:05:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:30:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:35:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...

ちなみに、以下のコマンドで抽出した部分だけ新規ファイルに書き出すことも可能

grep -E "SampleApp" test.log > extract_test.log

複数の文字列を指定して抽出する

「17:00:00」と「SampleApp」両方の文字列を含む行だけ抽出する場合は以下のコマンド

grep -E "17:00:00.*SampleApp" test.log.csv > extract_test.log

結果は以下のとおり。

2023-02-07 17:00:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...

抽出する文字列の順番を逆にすると出力されないので注意が必要。

#以下の場合は出力されないので注意
grep -E "SampleApp.*17:00:00" test.log.csv > extract_test.log

逆の場合でも抽出対象にしたい場合は以下のようにパイプを用いた記述にする

grep -E "17:00:00.*SampleApp|SampleApp.*17:00:00" test.log.csv > extract_test.log

特定の時間帯のログのみ抽出する

時間範囲を指定するにはワイルドカードを使う。[] を使用するとワイルドカード指定できる。17:00〜17:29までのログを抽出する時は以下のようなコマンドとなる

grep -E "17:[0-29]" test.log

抽出結果は以下のようになる

2023-02-07 17:00:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:05:00 SampleApp test.log [DEBUG] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:10:00 WebApp test.log [WARN] GET localhost:8080/:https//qiita/access/...
2023-02-07 17:15:00 WebApp test.log [WARN] GET localhost:8080/:https//qiita/access/...

膨大な量のログを相手にする時に便利

1
2
1

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