LoginSignup
11
11

More than 5 years have passed since last update.

Macで標準出力にタイムスタンプを割りこませたい

Last updated at Posted at 2016-06-19

ナウ :sunglasses: でヤング :triumph: な現代人 :briefcase: は時間にうるさい。
標準出力にタイムスタンプを割り込ませて、いろんなコマンドをナウ:sunglasses:でヤング:triumph:にしよう

環境

OS X 10.11
zsh
Homebrew 0.9.9

大丈夫だと思うけどHomebrewってナンヤネンって方はこちらを

Homebrewの導入手順

経緯 (興味ない方はパス :cyclone: )

linuxではstdbufコマンドで標準出力に割り込ませることが出来るらしい。
stdbufコマンドを使用してコマンドの標準出力にタイムスタンプを追加

Macでも出来るのか…?

~/
ping 8.8.8.8 | stdbuf -oL gawk '{print strftime("[%a %b %e %H:%M:%S %Z %Y] "), $0; }'
-----
zsh: command not found: stdbuf

...
どうやら出来ない。stdbufが入ってないそうな。
brew install stdbufでは入らず。

どうやらMacではstdbufそのものは使えないらしい。代替品のgstdbufが使えるそうな。
macで使いにくいコマンドをLinuxに合わせる

と、言うわけで

やってみよう。

方法

 準備

~/
brew install coreutils
brew install gnu-sed
brew install gawk

gstdbufが使えるようになった。

サンプル

~/
ping 8.8.8.8 | gstdbuf -oL gawk '{print strftime("[%a %b %e %H:%M:%S %Z %Y] "), $0; }'

月  6 20 02:18:16 JST 2016]  PING 8.8.8.8 (8.8.8.8): 56 data bytes
[月  6 20 02:18:16 JST 2016]  64 bytes from 8.8.8.8: icmp_seq=0 ttl=52 time=5.284 ms
[月  6 20 02:18:17 JST 2016]  64 bytes from 8.8.8.8: icmp_seq=1 ttl=52 time=4.061 ms
[月  6 20 02:18:18 JST 2016]  64 bytes from 8.8.8.8: icmp_seq=2 ttl=52 time=4.153 ms

strftimeはCのそれと大体一緒らしい。
Man page of STRFTIMEを参考にして

[%a %b %e %H:%M:%S %Z %Y] 

の中を適当にいじれば表示させる項目を変える事ができる。
やったぜ

追記

gawk単体でも同じことが出来るそうです。(KazBondさんありがとうございます)

~/
ping 8.8.8.8 | gawk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }{fflush()}'

gawkもデフォルトで入ってるかどうか失念してしまったので、出来なかったら

~/
brew install gawk

しましょう。

参考

stdbufコマンドを使用してコマンドの標準出力にタイムスタンプを追加
macで使いにくいコマンドをLinuxに合わせる
Man page of STRFTIME

11
11
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
11
11