LoginSignup
32
19

More than 5 years have passed since last update.

grep の出力をバッファさせない

Last updated at Posted at 2015-02-15

grep コマンドは、何もしないと出力をバッファする(一旦溜め込む)ようになっています。

あるファイル全体とか固定のデータに対して grep する場合は特に気にならないでしょう。
しかしストリーミングデータを扱う場合、例えば何らかのログファイルを tail -f したものに対して grep すると、複数行がまとめて遅延して出力されてしまいます。
ここは元のログが出力されると(ほぼ)同時に、リアルタイムに grep 結果も出力してほしいところです。

解決策: --line-buffered オプション

grep に --line-buffered オプションをつけると、出力がバッファされることなくリアルタイムに表示されるようになります!

$ tail -f /var/log/access.log | grep -E '\.png$' --line-buffered

--line-buffered は、「1行単位で出力させる」というオプションです。BSD grep と GNU grep ともに用意されているので、Mac ユーザも Linux ユーザも安心です。

man 見てみましょう。

BSD-grep
# grep (BSD grep) 2.5.1-FreeBSD

--line-buffered
    Force output to be line buffered.  By default, output is line buffered when standard output is a terminal and block buffered otherwise.
GNU-grep
# grep (GNU grep) 2.14

--line-buffered
    Use line buffering on output.  This can cause a performance penalty.

パフォーマンスが悪くなるかも、と書いてあります。状況によって使い分けましょう。

32
19
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
32
19