LoginSignup
0
0

More than 3 years have passed since last update.

複数ファイルの一行目の日付を抜き出すけど head を使わない方法

Last updated at Posted at 2019-05-16

たぶん方法は色々あると思うんだけど、下記のようなログファイルがあったとする。具体的に言うと、Let's Encryptのログがこんな感じなんだけど、その各ファイルの一行目の日時が欲しい。コマンドの実行日時を知りたいのだ。実行環境は macOS 10.14.5

$ ls
log1.log  log2.log  log3.log  log4.log  log5.log
$ head ./*
==> ./log1.log <==
2019/05/23 02:58:49,log1 desu
2019/05/23 02:58:50,log1 desu

==> ./log2.log <==
2019/07/06 02:58:53,log2 desu
2019/07/06 02:58:54,log2 desu

==> ./log3.log <==
2019/01/01 02:58:55,log3 desu
2019/01/01 02:58:56,log3 desu

==> ./log4.log <==
2019/09/23 02:58:57,log4 desu
2019/09/23 02:58:58,log4 desu

==> ./log5.log <==
2019/10/19 02:58:59,log5 desu
2019/10/19 02:59:00,log5 desu

一行目を取り出して、","までを出力すればいいから楽勝のはず。当然 head をまず使う。誰だってそうする。俺だってそうする。

$ head -n 1 ./* | cut -d , -f 1
==> ./log1.log <==
2019/05/23 02:58:49

==> ./log2.log <==
2019/07/06 02:58:53

==> ./log3.log <==
2019/01/01 02:58:55

==> ./log4.log <==
2019/09/23 02:58:57

==> ./log5.log <==
2019/10/19 02:58:59

楽勝だった。楽勝なんだけどちょっと思ってたのと違う。今回の場合はファイル名が不要だった。Macにデフォルトで入ってる head コマンドがファイル名を無視してくれない。マジかよ。オプションが下記しかない。何ならhelpもないって言っている。

$ head --help
head: illegal option -- -
usage: head [-n lines | -c bytes] [file ...]

GNUのheadであれば -q でファイル名除外できるので目的は達成できた。Macの標準だとないみたい。headコマンドを入れ替えるのが一番簡単だと思うけど、悔しいから他の方法考えた。

$ ls -1 | xargs -I {} sh -c 'sed -n 1P {}' | cut -d , -f 1
2019/05/23 02:58:49
2019/07/06 02:58:53
2019/01/01 02:58:55
2019/09/23 02:58:57
2019/10/19 02:58:59

こうしたかった。awkでもできるだろうし、もっとスマートな方法もあると思う。

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