0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csplit でファイル分割

Last updated at Posted at 2018-06-19

はじめに

コマンドの出力結果を定期的に取得します。1ファイルに取得時間とコマンドの出力の組み合わせでファイルサイズが大きくなります。時系列での比較をするのにファイルを分割したくなるので、その方法を調べました。

コマンドの出力取得例

ネットワークの状態変化を確認するのに、netstat -an を定期的に取得します。netstat.out に10秒間隔で出力されます。

netstat
$ while true
> do
> date +"%F %T" >> netstat.out
> netstat -an >> netstat.out
> sleep 10
> done

ファイルの分割

以下が定期的に出力されることになります。

netstat.out
2018-06-19 23:50:32
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     
...

以下のコマンドで日付の部分を先頭にして分割することができます。

  • -z .. 0 バイトのファイルができてしまったので指定しました。
  • -f .. netstat を prefixにして分割ファイルを出力
  • -n 3 .. suffix に使う数字の桁数 3 だと 000 から 999 まで、出来上がるファイル数で指定しておく。
    今回の場合だと grep "2018-06" netstat.out | wc -l で数を数えてから指定しました。
csplit
$ grep "2018-06" netstat.out | wc -l
41
$ csplit -z -f netstat -n 3 netstat.out /2018-06/ {*}

最初は grep で行数を確認して、この行数をもとに head と tail で取り出せないかと試行錯誤しまうところでしたが、探してみると見つかるもんですね。

grep
$ cat -n netstat.out | grep 2018-06
     1	2018-06-19 23:50:32
   852	2018-06-19 23:50:42
  1703	2018-06-19 23:50:52
  2554	2018-06-19 23:51:02
  3405	2018-06-19 23:51:12
  4256	2018-06-19 23:51:22
  5107	2018-06-19 23:51:32
  5958	2018-06-19 23:51:42
  6815	2018-06-19 23:51:52
  7672	2018-06-19 23:52:02
  8529	2018-06-19 23:52:12

参考

テキストファイルを任意の文字列で分割するには

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?